把文章内容中img替换为mip-img标签(包括结束标签)

在做百度熊掌号mip页面页面生成的过程中,也许你会遇到比如iframe标签和img等原生的html标签转换成mip标签的需求,类似的iframe倒是比较省事,直接替换开始结束标签就好了,但标准的img标签是没有结束标签的,所以替换的时候稍微复杂一点,下面是如何将img标签替换成mip-img标签的实现,补齐了结束标签。

function replaceMipImages(content)
{
    // 匹配所有的<img />
    preg_match_all('/<img (.*?)\>/',content, images);

    if(!is_null(images)) {
        foreach(images[1] asindex => value){mip_img = str_replace('<img', '<mip-img', images[0][index]);
            mip_img = str_replace('>', '></mip-img>',mip_img);
            //以下代码可根据需要修改/删除
            mip_img = preg_replace('/(width|height)="\d*"\s/', '',mip_img );//移除图片width|height
            mip_img = preg_replace('/ style=\".*?\"/', '',mip_img);//移除图片style
            mip_img = preg_replace('/ class=\".*?\"/', '',mip_img);//移除图片class
            //以上代码可根据需要修改/删除
            content = str_replace(images[0][index],mip_img, content);
        }
    }
    returncontent;
}

以上代码来自https://www.cnblogs.com/dongruiha/p/7644040.html,实测有效,各位根据需要自行修改即可使用。

把文章内容中img替换为mip-img标签(包括结束标签)

原文链接:https://beltxman.com/2141.html,若无特殊说明本站内容为 行星带 原创,未经同意禁止转载。

Scroll to top