替换作为逗号分隔列表一部分的字符串中的值。 PHP

Replace a value in a string that is part of a comma-separated list. PHP

我正在尝试替换逗号分隔列表中的名称。

但是,无法弄清楚如何匹配不区分大小写的确切名称,如果不完全匹配则不捕获

这是我到目前为止得到的。

$search  = "My name is Christina and this is another example";
$AllNames = "Lola,Chris,Monic";
$search = str_ireplace(array_map("trim", explode(",", strtolower($AllNames))), '****', $search);

所以在这种情况下克里斯蒂娜的名字将被标记为****,虽然我只是在寻找克里斯。 知道我如何才能做到这一点。

我找到了一些示例,说明如何将以逗号分隔的列表分解为数组,然后通过每个项目进行 foreach,但也许有更简单的解决方案。

尝试在值中使用 \b 单词边界以及 /i 不敏感修饰符 preg_replace:

$search  = "My name is Christina and this is another example, my friends are Lola and Monica and Monic and Chris. As lowercase: lola, christina, monic, monica, chris.";
$AllNames = ["/Lola/i", "/Chris\b/i", "/Monic\b/i"];
$search = preg_replace($AllNames, '****', $search);
echo $search;

输出:

My name is Christina and this is another example, my friends are **** and Monica and **** and ****. As lowercase: ****, christina, ****, monica, ****.

请注意,我没有在 Lola 中使用边界一词,但如果需要,可以轻松添加。