我希望替换字符串中src
标签的所有img
属性。
我的字符串:
$string = "some text with <img src='/uploads/images/5d0554.jpeg'> and
<img src='/uploads/images/507a.jpeg'> or <img src='/uploads/images/0a74.jpeg'> in it.";
应成为:
$string = "some text with <img src='some/value/one.jpeg'> and
<img src='alue/SomethingElse.png'> or <img src='Value3'> in it.";
我想做的事情:
$regex = '/< *img[^>]*src *= *["\']?([^"\']*)/i';
preg_match_all($regex, $string, $matches);
$srcMatches = $matches[1];
$replacementValues = ["some/value/one.jpeg", "value/SomethingElse.png", "Value3"];
preg_replace_callback($regex, function($matches) use (&$replacementValues) {
return array_shift($replacementValues);
}, $string);
这给了我
some long text with some/value/one.jpeg'> and
value/SomethingElse.png'> or Value3'> in it.
我也尝试使用preg_replace
,但是由于要替换的值中所有/
都给我带来了问题。
答案 0 :(得分:0)
此表达式可能会使用6个捕获组来替换:
$re = '/([\s\S]*?)(src=[\'"])\/uploads\/images\/.+?(\..+?)([\'"]>[\s\S]*?src=[\'"])\/uploads\/images\/.+?\..+?([\'"]>[\s\S]*?src=[\'"])\/uploads\/images\/.+?\..+?([\'"]>[\s\S]*)/m';
$str = 'some text with <img src=\'/uploads/images/5d0554.jpeg\'> and
<img src=\'/uploads/images/507a.jpeg\'> or <img src=\'/uploads/images/0a74.jpeg\'> in it.';
$subst = '$1$2some/value/one$3$4alue/SomethingElse\\.png$5Value3$6';
$result = preg_replace($re, $subst, $str);
echo $result;
some text with <img src='some/value/one.jpeg'> and
<img src='alue/SomethingElse.png'> or <img src='Value3'> in it.
jex.im可视化正则表达式: