Preg_replace与数组替换

Ale*_*lex 15 php regex string

$string = ":abc and :def have apples.";
$replacements = array('Mary', 'Jane');
Run Code Online (Sandbox Code Playgroud)

应成为:

Mary and Jane have apples.
Run Code Online (Sandbox Code Playgroud)

现在我这样做:

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

foreach($matches[0] as $index => $match)
   $string = str_replace($match, $replacements[$index], $string);
Run Code Online (Sandbox Code Playgroud)

我可以在一次运行中使用preg_replace之类的东西吗?

hak*_*kre 14

您可以使用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);
Run Code Online (Sandbox Code Playgroud)

输出:

Mary and Jane have apples.
Run Code Online (Sandbox Code Playgroud)


Qta*_*tax 8

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

echo preg_replace("/:\\w+/e", 'array_shift($replacements)', $string);
Run Code Online (Sandbox Code Playgroud)

输出:

Mary and Jane have apples.
Run Code Online (Sandbox Code Playgroud)


小智 7

试试这个

$to_replace = array(':abc', ':def', ':ghi');
$replace_with = array('Marry', 'Jane', 'Bob');

$string = ":abc and :def have apples, but :ghi doesn't";

$string = strtr($string, array_combine($to_replace, $replace_with));
echo $string;
Run Code Online (Sandbox Code Playgroud)

这是结果:http://sandbox.onlinephpfunctions.com/code/7a4c5b00f68ec40fdb35ce189d26446e3a2501c2

  • 这是最快的解决方案,因为它不使用正则表达式 (2认同)