[英]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);
所以在这种情况下,Christina 的名字将被标记为 ****,虽然我只是在寻找 Chris。 知道我如何实现这一目标。
我找到了一些关于如何将逗号分隔的列表分解为数组然后 foreach 遍历每个项目的示例,但也许有一个更简单的解决方案。
尝试使用值中的\\b
字边界以及带有preg_replace
/i
不敏感修饰符:
$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
使用词边界,但如果需要,可以轻松添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.