Home >Backend Development >PHP Problem >How to replace imgsrc address parameter in php

How to replace imgsrc address parameter in php

藏色散人
藏色散人Original
2020-07-18 10:10:562376browse

php替换imgsrc的方法:首先定义一个“get_img_thumb_url”方法;然后通过正则替换Img中src地址参数;最后将图片地址替换成压缩URL即可。

How to replace imgsrc address parameter in php

PHP实现用正则替换Img中src地址参数

在实际开发过程,我们往往需要PHP动态的去改变图片参数去达到图片压缩,或者图片裁剪功能,但是已经入库的老图片代码,如何能解决裁剪和压缩,这就用到了正则替换

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

输出结果:

<img src="https://www.xxx.com/styles/images/default.jpg-256E35">

推荐:《PHP教程

The above is the detailed content of How to replace imgsrc address parameter 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