使用阵列替换Preg_replace

2022-08-31 00:23:57
$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');

应变为:

Mary and Jane have apples.

现在我是这样做的:

preg_match_all('/:(\w+)/', $string, $matches);

foreach($matches[0] as $index => $match)
   $string = str_replace($match, $replacements[$index], $string);

我可以在一次运行中执行此操作,使用类似preg_replace?


答案 1

您可以与一个接一个地消耗替换项的回调一起使用:preg_replace_callback

$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');
echo preg_replace_callback('/:\w+/', function($matches) use (&$replacements) {
    return array_shift($replacements);
}, $string);

输出:

Mary and Jane have apples.

答案 2
$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');

echo preg_replace("/:\\w+/e", 'array_shift($replacements)', $string);

输出:

Mary and Jane have apples.

推荐