1、一个描述内容,形如:<p><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-1.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-2.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-3.jpg" /><br />
2、现在我的需求是批量替换src中的图片路径,能够改成路径为/upload/img/,请问正则改怎么写呢?
str_replace('file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/','/upload/img/',$str)
1.因为你的前缀是固定的话,用str_replace的效率其实更高的。
2.如果不是固定的话,可以参考以下的方法preg_replace_callback
3.调试记得用查看源代码的形式。
<?php
$str = '<p><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-1.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-2.jpg" /><br /><img src="file:///C:/Users/Administrator/Desktop/测试/data/5201608091357/contentPic/麻短裙16/1643805e-3.jpg" /><br />';
echo $str;
$pregRule = "/file:\/\/\/C:\/Users\/Administrator\/Desktop\/测试\/data\/5201608091357\/contentPic\//";
$result = preg_replace_callback($pregRule, function(){
return "/upload/img/";
}, $str);
echo $result;