用其他值的数组替换字符串中的值

时间:2019-06-15 22:13:06

标签: php regex

我希望替换字符串中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,但是由于要替换的值中所有/都给我带来了问题。

1 个答案:

答案 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.

Demo

RegEx电路

jex.im可视化正则表达式:

enter image description here