本文实例讲述了php基于正则批量替换img中src内容实现获取缩略图的功能。分享给大家供大家参考,具体如下:
这里php用正则批量替换img中src内容,实现获取图片路径缩略图的功能
网上很多正则表达式只能获取或者替换一个img的src内容,或者只能替换固定的字符串,要动态替换多个图片内容的试了几个小时才解决。
/**
* 图片地址替换成压缩url
* @param string $content 内容
* @param string $suffix 后缀
*/
function get_img_thumb_url($content="",$suffix="!c550x260.jpg")
{
$pregrule = "/<[img|img].*?src=['|"](.*?(?:[.jpg|.jpeg|.png|.gif|.bmp]))['|"].*?[/]?>/";
$content = preg_replace($pregrule, '<img src="${1}'.$suffix.'" style="max-width:100%">', $content);
return $content;
}
实例使用代码:
$content = '<a href="#" rel="external nofollow" rel="external nofollow" ><img class="center" src="https://xxx.com/styles/images/default.jpg"></a>'
.'<p><img class="center" src="https://img.xxx.com/images/219_ig5ezi.jpg" style="max-width: 100%;"></p>';
$newct = get_img_thumb_url($content);
print_r($newct);
输出结果:
复制代码 代码如下:
<a href="#" rel="external nofollow" rel="external nofollow" ><img src="https://xxx.com/styles/images/default.jpg!c550x260.jpg" style="max-width:100%"></a><p><img src="https://img.xxx.com/images/219_ig5ezi.jpg!c550x260.jpg" style="max-width:100%"></p>
ps:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:
javascript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript
正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg
更多关于php相关内容感兴趣的读者可查看本站专题:《php正则表达式用法总结》、《php数组(array)操作技巧大全》、《php基本语法入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家php程序设计有所帮助。
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:)!