php Preg_replace 与数组替换

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9416175/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 06:46:26  来源:igfitidea点击:

Preg_replace with array replacements

phpregexstring

提问by Alex

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

should become:

应该变成:

Mary and Jane have apples.

Right now I'm doing it like this:

现在我是这样做的:

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

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

Can I do this in a single run, using something like preg_replace?

我可以在一次运行中使用 preg_replace 之类的东西吗?

采纳答案by hakre

You could use preg_replace_callbackwith a callback that consumes your replacements one after the other:

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

Output:

输出:

Mary and Jane have apples.

回答by Qtax

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

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

Output:

输出:

Mary and Jane have apples.

回答by Diyar Baban

Try this

尝试这个

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

here is result: http://sandbox.onlinephpfunctions.com/code/7a4c5b00f68ec40fdb35ce189d26446e3a2501c2

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

回答by Miguel

For a Multiple and Full array replacement by Associative Key you can use this to match your regex pattern:

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

   $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_

*Notice, thats although "_no_match_" lacks translation, it will match during regex, but preserve its key. And keys can repeat many times.

*注意,尽管“_no_match_”缺少翻译,它会在正则表达式中匹配,但保留其键。并且键可以重复多次。