php - 使用关联数组替换字符串中的几个单词,保持原始大小写不变

标签 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)。

我不太了解正则表达式(这让我眼花缭乱),无法通过为跨度标题添加第二个变量来更改它:

$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);

最佳答案

您可以循环运行此替换:

$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;

关于php - 使用关联数组替换字符串中的几个单词,保持原始大小写不变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32746075/

相关文章:

python - 仅在 pandas 数据框中查找字符串并用数字替换字符串

php - 如何在MySQL中检索两个日期之间的所有行?

php - 当条件相同时,如何对多列使用一次 CASE 语句?

c - 如何在C中一一获取字符串的输入

regex - 在大写字母前插入空格但不在缩写之间插入空格的 pythonic 方法

python - Pandas 删除括号之间的字符

python - 子字符串在字符串中的位置

php - 如何从字符串中查找特定值

php - 如何使用迁移插件将 tinyint 添加到 cakephp 3 中的数据库字段?

PHP mkdir 不工作——可能与 Mac 本地主机有关