[英]Replace a value in a string that is part of a comma-separated list. PHP
I am trying to replace a name that is part of a comma-separated list.我正在尝试替换作为逗号分隔列表一部分的名称。
However, cannot figure out how to do it to match the exact name case insensitive and not catch if is not the exact match但是,无法弄清楚如何匹配不区分大小写的确切名称,如果不是完全匹配,则不捕获
Here is what I got so far.这是我到目前为止所得到的。
$search = "My name is Christina and this is another example";
$AllNames = "Lola,Chris,Monic";
$search = str_ireplace(array_map("trim", explode(",", strtolower($AllNames))), '****', $search);
So in this case The name of Christina will be marked as ****, although I am looking for Chris only.所以在这种情况下,Christina 的名字将被标记为 ****,虽然我只是在寻找 Chris。 Any idea how I can achieve that.
知道我如何实现这一目标。
I found some examples on how to do it if I explode the comma-separated list into an array and then foreach trough each item, but perhaps there is an easier solution.我找到了一些关于如何将逗号分隔的列表分解为数组然后 foreach 遍历每个项目的示例,但也许有一个更简单的解决方案。
Try the \\b
word boundary in the values along with /i
insensitive modifiers with preg_replace
:尝试使用值中的
\\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;
Output:输出:
My name is Christina and this is another example, my friends are **** and Monica and **** and ****. As lowercase: ****, christina, ****, monica, ****.
Note that I did not use the word boundary with Lola
, but that can be easily added, if needed.请注意,我没有在
Lola
使用词边界,但如果需要,可以轻松添加。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.