PHP基于正则批量替换Img中src内容实现获取缩略图的功能示例

yipeiwu_com6年前PHP代码库

本文实例讲述了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=[\'|\"](.*?(?:[\.jpg|\.jpeg|\.png|\.gif|\.bmp]))[\'|\"].*?[\/]?>/";
$content = preg_replace($pregRule, '<img src="${1}'.$suffix.'" style="max-width:100%">', $content);
return $content;
}

实例使用代码:

$content = '<a href="#" rel="external nofollow" rel="external nofollow" ><img class="center" src="/zb_users/upload/202003/p4lxm30swlo.jpg"></a>'
.'<p><img class="center" src="/zb_users/upload/202003/i4oljpt2i2o.jpg" style="max-width: 100%;"></p>';
$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>

PS:这里再为大家提供2款非常方便的正则表达式工具供大家参考使用:

JavaScript正则表达式在线测试工具:
http://tools.jb51.net/regex/javascript

正则表达式在线生成工具:
http://tools.jb51.net/regex/create_reg

更多关于PHP相关内容感兴趣的读者可查看本站专题:《php正则表达式用法总结》、《PHP数组(Array)操作技巧大全》、《PHP基本语法入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家PHP程序设计有所帮助。

相关文章

PHP基于工厂模式实现的计算器实例

本文实例讲述了PHP基于工厂模式实现的计算器。分享给大家供大家参考。具体如下: abstract class Calculator { private $number1; pr...

php算开始时间到过期时间的相隔的天数

复制代码 代码如下://mktime = mktime($hours,minute,seconds,month,day,years) $start_time = mktime(0,0,0...

php中echo()和print()、require()和include()等易混淆函数的区别

1.echo和print的区别 PHP中echo和print的功能基本相同(输出),但是两者之间还是有细微差别的。echo输出后没有返回值,但print有返回值,当其执行失败时返回fla...

php做下载文件的实现代码及文件名中乱码解决方法

最近有人问我做下载文件的方法,对于php方法如下: 复制代码 代码如下: <?php header("Content-Type: application/force-downloa...

WordPress中获取页面链接和标题的相关PHP函数用法解析

get_permalink()(获取文章或页面链接) get_permalink() 用来根据固定连接返回文章或者页面的链接。在获取链接时 get_permalink() 函数需要知道要...