如题
现在有一字符串是
$content = '
test
';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; }
test
$content = '<p><img src="http://localhost:8080/story/images/tmp/1403530150545.jpg" style="max-width:90%" alt="求替换全局img图片的正则表达式" ><img src="http://localhost:8080/story/images/tmp/1403530147265.jpg" style="max-width:90%" alt="求替换全局img图片的正则表达式" >test</p>';$content = preg_replace('#(?<=src="http://localhost:8080/story/images/)tmp/#', 'pub/', $content);echo $content;
test
你没有防止贪婪匹配。
$pattern='/()/';
你写的方法加一个参数U就可以了。
加上U,将懒惰匹配 变成 贪婪匹配。
$pattern='/()/ U';
测试例子:
$content = '<p><img src="http://localhost:8080/story/images/tmp/1403530150545.jpg" style="max-width:90%" alt="求替换全局img图片的正则表达式" ><img src="http://localhost:8080/story/images/tmp/1403530147265.jpg" style="max-width:90%" alt="求替换全局img图片的正则表达式" >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;}
test