【问题标题】:Preg_replace with array replacementsPreg_replace 与数组替换
【发布时间】:2012-03-14 01:01:40
【问题描述】:
$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 之类的东西一次运行吗?

【问题讨论】:

  • This 是使用关联数组的方法。

标签: php regex string


【解决方案1】:

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

【讨论】:

    【解决方案2】:
    $string = ":abc and :def have apples.";
    $replacements = array('Mary', 'Jane');
    
    echo preg_replace("/:\\w+/e", 'array_shift($replacements)', $string);
    

    输出:

    Mary and Jane have apples.
    

    【讨论】:

    • PHP 7.0 不支持。
    【解决方案3】:

    试试这个

    $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

    【讨论】:

    • 这是最快的解决方案,因为它不使用正则表达式
    【解决方案4】:

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

       $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_”缺少翻译,但它会在正则表达式中匹配,但是 保留其密钥。并且键可以重复多次。

    【讨论】:

    • 我建议在正则表达式中添加“u”修饰符以支持 UTF-8 字符串:/\b_(\w*)_\b/u。顺便说一句,上面的代码有语法错误,末尾有多余的括号。
    • 看起来没有额外的括号问题,我验证了代码并且运行正常。但是我添加了 UTf-8。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2014-06-10
    • 2011-01-24
    • 2015-08-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多