$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 之类的东西在单次运行中完成吗?
最佳答案
您可以将 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.
关于php - Preg_replace 与数组替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9416175/