使用preg_replace中的数组来减少代码


Using an array in preg_replace to reduce codes

是否可以在preg_replace中使用数组来减少所需的代码?像这样:

$text = "1 2 3";
$array = array(1 => "one", 2 => "two", 3 => "three");
preg_replace($array, $text);
echo $text;

结果:

1 2 3

所需结果:

one two three

mixed preg_replace (mixed $pattern, mixed $replacement, mixed $subject,…<一口> preg_replace

$text = "1 2 3";
$array = array(
'/1/' => "one",
'/2/' => "two",
'/3/' => "three");
$text = preg_replace(array_keys($array), $array, $text);

演示在eval。在

中(正如在注释中提到的,这里不需要使用正则表达式)