为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
扬帆大鱼 2023-12-15 10:42:00
我正在尝试替换逗号分隔列表中的名称。但是,无法弄清楚如何匹配确切的名称,不区分大小写,并且如果不完全匹配则不捕获这是我到目前为止所得到的。$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。 知道我如何才能实现这一目标。我找到了一些示例,说明如何将逗号分隔的列表分解为数组,然后遍历每个项目,但也许有一个更简单的解决方案。
查看完整描述

1 回答

?
一只名叫tom的猫

TA贡献1906条经验 获得超2个赞

尝试使用值中的 \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 中使用单词边界,但如果需要,可以轻松添加。


查看完整回答
反对 回复 2023-12-15
  • 1 回答
  • 0 关注
  • 44 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信