Home  >  Article  >  Backend Development  >  How to replace src in php

How to replace src in php

王林
王林Original
2020-11-03 14:48:541629browse

php替换src的方法:可以利用preg_replace函数并结合正则表达式来实现替换,如【preg_replace($pregRule, 'How to replace src in php

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

函数介绍:

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

(推荐教程:php视频教程

实现代码:

/**
* 图片地址替换成压缩URL
* @param string $content 内容
* @param string $suffix 后缀
*/
function get_img_thumb_url($content="",$suffix="!c550x260.jpg")
{
$pregRule = "/<[img|IMG].*?src=[\&#39;|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\&#39;|\"].*?[\/]?>/";
$content = preg_replace($pregRule, &#39;<img src="${1}&#39;.$suffix.&#39;" style="max-width:100%">&#39;, $content);
return $content;
}

实际代码:

$content = &#39;<a href="#"><img class="center" src="https://xxx.com/styles/images/default.jpg"></a>&#39;
.&#39;<p><img class="center" src="https://img.xxx.com/images/219_Ig5eZI.jpg" style="max-width: 100%;"></p>&#39;;
$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培训

The above is the detailed content of How to replace src in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn