Preg_replace与数组替换

时间:2012-02-23 15:36:32

标签: php regex string

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

应该成为:

Mary and Jane have apples.

现在我这样做:

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

foreach($matches[0] as $index => $match)
   $string = str_replace($match, $replacements[$index], $string);

我可以使用preg_replace吗?

在一次运行中完成此操作

4 个答案:

答案 0 :(得分:12)

您可以将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);

输出:

Mary and Jane have apples.

答案 1 :(得分:8)

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

echo preg_replace("/:\\w+/e", 'array_shift($replacements)', $string);

输出:

Mary and Jane have apples.

答案 2 :(得分: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;

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

答案 3 :(得分:3)

对于通过关联键替换多个和完整数组,您可以使用它来匹配您的正则表达式模式:

   $words=array("_saudation_"=>"Hello", "_animal_"=>"cat", "_animal_sound_"=>"MEooow");
   $source=" _saudation_! My Animal is a _animal_ and it says _animal_sound_ ... _animal_sound_ ,  _no_match_";


  function translate_arrays($source,$words){
    return (preg_replace_callback("/\b_(\w*)_\b/u", function($match) use ($words) {    if(isset($words[$match[0]])){ return ($words[$match[0]]); }else{ return($match[0]); } },  $source));
  }


    echo translate_arrays($source,$words);
    //returns:  Hello! My Animal is a cat and it says MEooow ... MEooow ,  _no_match_

*注意,那就是" _no_match _"缺乏翻译,它会在正则表达式中匹配,但是 保留它的钥匙。钥匙可以重复多次。