替换作为逗号分隔列表一部分的字符串中的值。 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);

所以在这种情况下 Christina 的名字将被标记为 ****,尽管我只是在寻找 Chris。 知道我如何才能实现这一目标。


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


扬帆大鱼
浏览 51回答 1
1回答

一只名叫tom的猫

尝试使用值中的 \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 中使用单词边界,但如果需要,可以轻松添加。
打开App,查看更多内容
随时随地看视频慕课网APP