如题
现在有一字符串是
$content = 'e388a4556c0f65e1904146cc1a846bee7f702f3ca359a8316ab7f6c2174ccb51422e11ce720abdc65bbb88e354b73fa3test94b3e26ee717c64999d7867364b1b4a3';
想要将这字符里面的 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; }
$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;e388a4556c0f65e1904146cc1a846beef7e47314f1a6e7f596010d59064d9c86a797f9433274ebb9e9b6d857b3ba5c4dtest94b3e26ee717c64999d7867364b1b4a3
你没有防止贪婪匹配。
$pattern='/(95625772270bb853729b8db8d6da1966)/';
你写的方法加一个参数U就可以了。
加上U,将懒惰匹配 变成 贪婪匹配。
$pattern='/(435841a4cd43318b827e7ec2b37c9807)/ 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;}