2015-10-13 76 views
1

是否有可能使用的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 
+5

'strtr函数的效率($文本,$ array);' – Rizier123

+0

@ Rizier123是的!有用! strtr代表什么?字符串的东西,对吧? tr代表什么? – frosty

+1

@ Rizier123你好:)作出这样一个答案! –

回答

0

混合的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(如在评论中提到的,就没有必要使用正则表达式在这里)