【问题标题】:Escaping words in Preg MatchPreg Match 中的转义词
【发布时间】:2014-07-08 07:44:43
【问题描述】:

我有一个要在字符串 ($text) 中突出显示的单词列表(在数组中)。这是我的代码

$text = " A string with a spans  and color highlighted";
$words = array('and','span');

    foreach($words as $word){
      $patterns[] = '/'.$word.'/i';
    }

    foreach($words as $word){
      $replacements[] = "<span style='color:red;font-weight:bold;'>".$word."</span>";
    }

echo preg_replace($patterns, $replacements, $text);

我想替换 $text 中的单词 span 和 color,但结果有所不同,它还替换了 html 标签 span。我该如何克服这个问题。或者我可以有其他选择吗?

您可以在此处重现问题。 http://writecodeonline.com/php/

提前致谢。

【问题讨论】:

    标签: php regex preg-replace


    【解决方案1】:

    您不需要为列表中的每个单词生成模式和替换字符串。您只需要构建一个模式和一个带有反向引用的替换字符串:

    $text = " A string with a span  and color highlighted";
    $words = array('and', 'span');
    
    $pattern = '~\b(?:' . implode('|', $words) . ')\b~';
    
    $replacement  = '<span style="color:red;font-weight:bold;">$0</span>';
    
    $result = preg_replace($pattern, $replacement, $text);
    

    在替换字符串中,反向引用$0 指的是整个匹配结果。

    由于你只解析字符串一次,你就避免了这个问题。

    【讨论】:

    • 谢谢,这就是我要找的。​​span>
    【解决方案2】:

    这是一个更简单的解决方案,使用explode 函数:

    $text = "A string with a span and color highlighted";
    $words = array('and','span');
    $exploded = explode(" ", $text);
    $i = 0;
    foreach ($exploded as $word) {
        if (in_array($word, $words)) {
            $exploded[$i] = "<span style='color:red;font-weight:bold;'>".$word."</span>";
        }
        $i++;
    }
    print_r($exploded);
    

    结果:

        Array
    (
        [0] => A
        [1] => string
        [2] => with
        [3] => a
        [4] => <span style='color:red;font-weight:bold;'>span</span>
        [5] => <span style='color:red;font-weight:bold;'>and</span>
        [6] => color
        [7] => highlighted
    )
    

    【讨论】:

      猜你喜欢
      • 2018-02-22
      • 1970-01-01
      • 1970-01-01
      • 2017-02-28
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多