php中替换src的方法

发布时间:2020-11-04 10:09:16 作者:小新
来源:亿速云 阅读:166

这篇文章主要介绍php中替换src的方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

php替换src的方法:可以利用preg_replace函数并结合正则表达式来实现替换,如【preg_replace($pregRule, '<img src="${1}'.$suffix,$content);】。

可以使用正则表达式批量替换Img中src内容。

函数介绍:

preg_replace 函数执行一个正则表达式的搜索和替换。

实现代码:

/**
* 图片地址替换成压缩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="#"><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>

以上是php中替换src的方法的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

推荐阅读:
  1. 怎么在java中利用正则替换img标签中src值
  2. 如何在php中替换img中src内容

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

php src sr

上一篇:如何解决mysql大表查询慢的问题

下一篇:php有哪些设置目录权限的方法

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》