简体   繁体   English

在preg_replace中使用数组以减少代码

[英]Using an array in preg_replace to reduce codes

Is it possible to use an array in preg_replace to reduce the codes needed? 是否可以在preg_replace中使用数组来减少所需的代码? So, something like this: 因此,如下所示:

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

preg_replace($array, $text);

echo $text;

Result: 结果:

1 2 3

Needed Result: 所需结果:

one two three

mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject,... preg_replace 混合的preg_replace( 混合 $模式, 混合 $更换,混合$主题,... 的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) eval.in上的演示 (如评论中所述,此处无需使用正则表达式)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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