PHP preg_match_all搜索和替换

Ale*_*owe 8 php regex search replace preg-match

我已经尝试了大约一百万个不同的正则表达式,我无法绕过这一个(不可否认,很多正则表达式都不在我的掌握之中).

在我的文本中,我有这样的变量:

{{$one}}
{{$three.four.five}}
{{$six.seven}}
Run Code Online (Sandbox Code Playgroud)

我有一个包含所有替换的数组('one'的索引是'one'等)但有些可能会丢失.

我想从数组中替换它是否存在,如果不是单独保留文本.

我可以使用什么正则表达式在下面的代码段中的$ text中preg_match_all变量,在适当的地方替换$ replace并回显到浏览器?

<?php
    $replaces = array('testa.testb.testc' => '1', 'testc.testa' => '2', 'testf' => '3');
    $text = '{{$testa.testb.testc}}<br>{{$testc.testa}}<br>{{$testf}}<br>{{$aaaaa}}<br>';

    preg_match_all('/\{\{\$(\w+)\}\}/e', $text, $matches);

    foreach($matches as $match)
    {
        $key = str_replace('{{$', '', $match);
        $key = str_replace('}}', '', $key);

        if(isset($replaces[$key]))
            $text = str_replace($match, $replaces[$key], $text);
    }

    // I want to end up echo'ing:
    //   1<br>2<br>3<br>{{$aaaaa}}<br>

    echo $text;
?>
Run Code Online (Sandbox Code Playgroud)

http://codepad.viper-7.com/4INvEE

这个:

'/\{\{\$(\w+)\}\}/e'
Run Code Online (Sandbox Code Playgroud)

就像在片段中一样,是我得到的最接近的.

它也必须使用变量名中的do.

在此先感谢您的帮助!

Ham*_*mZa 8

这是一个非常好的使用案例,preg_replace_callback()但首先让我们改进你的正则表达式:

  1. 摆脱e修饰符,它已被弃用,你不需要它,因为我们将要使用它preg_replace_callback()

    /\{\{\$(\w+)\}\}/
    
    Run Code Online (Sandbox Code Playgroud)
  2. {{}}在这种情况下,我们不需要逃避,PCRE 足够聪明,可以说它们不是量词

    /{{\$(\w+)}}/
    
    Run Code Online (Sandbox Code Playgroud)
  3. 由于您的输入中有点,我们需要更改\w否则它将永远不会匹配.[^}]是完美的,因为它意味着匹配除了}

    /{{\$([^}]+)}}/
    
    Run Code Online (Sandbox Code Playgroud)
  4. 我倾向于使用不同的分隔符,这不是必需的:

    #{{\$([^}]+)}}#
    
    Run Code Online (Sandbox Code Playgroud)

让我们开始认真的生意,这里的use标识符会有很大的帮助:

$replaces = array('testa.testb.testc' => '1', 'testc.testa' => '2', 'testf' => '3');
$text = '{{$testa.testb.testc}}<br>{{$testc.testa}}<br>{{$testf}}<br>{{$aaaaa}}<br>';

$output = preg_replace_callback('#{{\$([^}]+)}}#', function($m) use ($replaces){
    if(isset($replaces[$m[1]])){ // If it exists in our array
        return $replaces[$m[1]]; // Then replace it from our array
    }else{
        return $m[0]; // Otherwise return the whole match (basically we won't change it)
    }
}, $text);

echo $output;
Run Code Online (Sandbox Code Playgroud)

Online regex demo Online php demo

  • 惊人!从上到下做出充分的解释.谢谢. (2认同)