php正则匹配重写html图片img路径

有时候,需要替换html内容中的图片img路径,可以考虑使用 PHP 正则表达式匹配并进行替换,效果不错。有需要的朋友,可以参考下。

1、正则写法:
1 <?php
2 $str = <<<EOF
3 <img src="uploads/images/20100318/20100318_1.gif">
4 <img src="file/20100318_2.jpg">
5 <img src="swfup/20100318_3.png">
6 EOF;
7 echo '替换前:<pre>',htmlentities($str),'</pre><hr align=left width=320px/>';
8 echo '替换后:<pre>',htmlentities(preg_replace('/(<img.+?src=")[^"]+(\/.+?>)/','$1file$2', $str)),'</pre>';
9 ?>

2、替换操作
替换前: 

<img src="uploads/images/20100318/20100318_1.gif">
<img src="file/20100318_2.jpg">
<img src="swfup/20100318_3.png">

替换后:

<img src="file/20100318_1.gif">
<img src="file/20100318_2.jpg">
<img src="file/20100318_3.png">

您可能感兴趣的文章:
php匹配图片地址的代码一例
PHP正则匹配日期和时间(时间戳转换)的例子
php匹配任何网址的正则表达式
PHP正则匹配获取URL中域名的代码
使用 preg_replace 函数 匹配图片并加上链接的方法
php用preg_match_all匹配文章中的图片
php正则表达式匹配URL中的域名

你可能感兴趣的:(图片img路径,php正则)