使用关联数组替换字符串中的多个单词,保持原始大小写不变
我要将数组与文本字符串进行匹配,其中与数组键匹配的单词将替换为具有匹配数组值的标题的SPAN标记。
我可以使用str_iplace执行此操作,但是匹配的单词会丢失大小写:
$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);
php>
您可以使用一些常用的推荐答案函数来实现。
从您的
keys
创建一个模式数组,以便使用preg_replace_callback
以不区分大小写的方式进行搜索。将
$glossary
传递给preg_replace_callback
中的匿名函数,并根据当前匹配值的小写获取值(<span>
标题),找到后,将小写的wordX
替换为匹配。
这是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);
相关文章