Home  >  Article  >  Backend Development  >  Detailed explanation of the functional code for obtaining thumbnails using PHP by replacing src content in Img in batches based on regular expressions

Detailed explanation of the functional code for obtaining thumbnails using PHP by replacing src content in Img in batches based on regular expressions

怪我咯
怪我咯Original
2017-06-16 10:36:471408browse

这篇文章主要介绍了PHP基于正则批量替换Img中src内容实现获取缩略图的功能,涉及php针对页面img元素的正则匹配与替换操作相关实现技巧,需要的朋友可以参考下

本文实例讲述了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=[\&#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="#" rel="external nofollow" rel="external nofollow" ><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="#" 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>


The above is the detailed content of Detailed explanation of the functional code for obtaining thumbnails using PHP by replacing src content in Img in batches based on regular expressions. 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