Home > Article > Backend Development > How to use regular expression to replace img src in php
php正则替换img src的实现方法:首先定义一个“get_img_thumb_url”方法;然后通过“preg_replace($pregRule, '
推荐:《PHP视频教程》
PHP用正则批量替换Img中src内容,用正则表达式获取图片路径实现缩略图功能
网上很多正则表达式只能获取或者替换一个img的src内容,或者只能替换固定的字符串,要动态替换多个图片内容的试了几个小时才解决。
/** * 图片地址替换成压缩URL * @param string $content 内容 * @param string $suffix 后缀 */ function get_img_thumb_url($content="",$suffix="!c550x260.jpg") { // by http://www.manongjc.com/article/1319.html $pregRule = "/<[img|IMG].*?src=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/"; $content = preg_replace($pregRule, '<img src="${1}'.$suffix.'" style="max-width:100%">', $content); return $content; }
实例使用代码:
//by http://www.manongjc.com $content = '<a href="#"><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="#"><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>
The above is the detailed content of How to use regular expression to replace img src in php. For more information, please follow other related articles on the PHP Chinese website!