使用关联数组替换字符串中的多个单词,保持原始情况不变

时间:2015-09-23 17:41:16

标签: php regex string preg-replace

我希望将数组与文本字符串匹配,其中与数组键匹配的单词将替换为带有匹配数组值的标题的span标记。

我可以用str_ireplace做到这一点,但匹配的单词会失败:

$glossary = array(
    'word1' => '<span title="Explanation for Word 1">word1</span>',
    'word2' => '<span title="Explanation for Word 2">word2</span>',
    'word3' => '<span title="Explanation for Word 3">word3</span>'
);

$text = "This is a text about Word1. We also talk about word2 and WORD3. Also woRd3, word2 and WORD1";

list($keys, $values) = array_divide($glossary);

$result = str_ireplace($keys, $values, $text);

如上所述,这有效,但在此解决方案中,所有匹配的单词都将为小写。

我想要实现的目标是:

'This is a text about <span title="Explanation for Word 1">Word1</span>. 
We also talk about <span title="Explanation for Word 2">word2</span> and
<span title="Explanation for Word 3">WORD3</span>.
Also <span title="Explanation for Word 3">woRd3</span>, 
<span title="Explanation for Word 2">word2</span>
and <span title="Explanation for Word 1">WORD1</span>'

进行替换并保持案例完整

我发现了一个很好的回复,但它只适用于在匹配的单词周围添加span标记,它不会为标题添加第二个变量(php str_ireplace without losing case)。

我不知道足够的正则表达式(令我眼花缭乱)通过为span标题添加第二个变量来改变它:

$txt = 'Hi! How are you doing? Have some stars: * * *!';
$array_of_words = array('Hi!', 'stars', '*');

$pattern = '#(?<=^|\W)(' 
       . implode('|', array_map('preg_quote', $array_of_words))
       . ')(?=$|\W)#i';

echo preg_replace($pattern, 
      "<span style='background-color:#EEEE00'>$1</span>", $txt);

2 个答案:

答案 0 :(得分:1)

您可以使用一些常见的PHP函数来实现它。

  1. keys创建一系列模式,使用preg_replace_callback以不区分大小写的方式进行搜索。

  2. $glossary传递给preg_replace_callback中的匿名函数,并通过小写的当前匹配值获取值(<span>标题),找到后,替换小写wordX匹配。

  3. 这是PHP code

    $pttrns = array_map(function ($val) {return "/" . preg_quote($val) . "/i"; },
                      array_keys($glossary));                                    // Step 1
    $res = preg_replace_callback($pttrns, function ($m) use($glossary){          // Step 2
        return str_replace(strtolower($m[0]), $m[0],              
                                         $glossary[strtolower($m[0])]);         // Step 3
    }, $text);
    

答案 1 :(得分:0)

您可以在循环中运行此替换:

$txt = 'Hi! How are you doing? Have some stars: * * *!';
$glossary = array(
    'Hi!'   => 'title 1',
    'stars' => 'title 2',
    '*'     => 'title 3'
);
$result = $txt;
foreach ($glossary as $keyword => $title) {
    $pattern = '#(?<=^|\W)('.preg_quote($keyword).')(?=$|\W)#i';
    $result  = preg_replace($pattern, "<span title='{$title}'>$1</span>", $result);
}
echo $result;