简体   繁体   中英

Using an array in preg_replace to reduce codes

Is it possible to use an array in preg_replace to reduce the codes needed? So, something like this:

$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);

Demo at eval.in (as mentioned in the comments, there is no need to use regex here)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM