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

可以使用正则表达式批量替换Img中src内容。
函数介绍:
preg_replace 函数执行一个正则表达式的搜索和替换。
(推荐教程:php视频教程)
立即学习“PHP免费学习笔记(深入)”;
实现代码:
/**
* 图片地址替换成压缩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培训
以上就是php怎么替换src的详细内容,更多请关注php中文网其它相关文章!
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号