当前位置: 代码迷 >> PHP >> 求轮换全局img图片的正则表达式
  详细解决方案

求轮换全局img图片的正则表达式

热度:353   发布时间:2016-04-28 19:00:02.0
求替换全局img图片的正则表达式
如题
现在有一字符串是

$content = '<p><img src="http://localhost:8080/story/images/tmp/1403530150545.jpg" style="width: 268px;"><img src="http://localhost:8080/story/images/tmp/1403530147265.jpg" style="width: 268px;">test</p>';

想要将这字符里面的 images/tmp 都替换成 images/pub

本人已经写了一个函数


public static function replace_img_publish_path($content){
$pattern='/(<[img|IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg|gif|bmp|bnp|png)\"?.+>)/';
$replacement="\${1}images/pub/\${3}";
print  preg_replace($pattern, $replacement, $content);
exit;
}



输出结果为

<p><img src="http://localhost:8080/story/images/tmp/1403530150545.jpg" style="width: 268px;"><img src="http://localhost:8080/story/images/pub/1403530147265.jpg" style="width: 268px;">test</p>

只替换了最后一个img标签

如何才能全部都替换?
------解决方案--------------------
$content = '<p><img src="http://localhost:8080/story/images/tmp/1403530150545.jpg" style="width: 268px;"><img src="http://localhost:8080/story/images/tmp/1403530147265.jpg" style="width: 268px;">test</p>';

$content = preg_replace('#(?<=src="http://localhost:8080/story/images/)tmp/#', 'pub/', $content);
echo $content;
<p><img src="http://localhost:8080/story/images/pub/1403530150545.jpg" style="width: 268px;"><img src="http://localhost:8080/story/images/pub/1403530147265.jpg" style="width: 268px;">test</p>

------解决方案--------------------
你没有防止贪婪匹配。

 $pattern='/(<[img
------解决方案--------------------
IMG].+?src=\"?.+?)(images\/tmp\/)(.+?\.(jpg
------解决方案--------------------
gif
------解决方案--------------------
bmp
------解决方案--------------------
bnp
------解决方案--------------------
png)\"?.+?>)/';
------解决方案--------------------
你写的方法加一个参数U就可以了。
加上U,将懒惰匹配 变成 贪婪匹配。

$pattern='/(<[img
------解决方案--------------------
IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg
------解决方案--------------------
gif
------解决方案--------------------
bmp
------解决方案--------------------
bnp
------解决方案--------------------
png)\"?.+>)/U';

测试例子:

$content = '<p><img src="http://localhost:8080/story/images/tmp/1403530150545.jpg" style="width: 268px;"><img src="http://localhost:8080/story/images/tmp/1403530147265.jpg" style="width: 268px;">test</p>';

replace_img_publish_path($content);

function replace_img_publish_path($content){
    $pattern='/(<[img
------解决方案--------------------
IMG].+src=\"?.+)(images\/tmp\/)(.+\.(jpg
------解决方案--------------------
gif
------解决方案--------------------
bmp
------解决方案--------------------
bnp
------解决方案--------------------
png)\"?.+>)/U';
    $replacement="\${1}images/pub/\${3}";
    print  preg_replace($pattern, $replacement, $content);
    exit;
}


替换后:
<p><img src="http://localhost:8080/story/images/pub/1403530150545.jpg" style="width: 268px;"><img src="http://localhost:8080/story/images/pub/1403530147265.jpg" style="width: 268px;">test</p>