【问题标题】:Replace a value in a string that is part of a comma-separated list. PHP替换作为逗号分隔列表一部分的字符串中的值。 PHP
【发布时间】:2023-03-14 08:49:02
【问题描述】:

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

但是,无法弄清楚如何做到这一点以匹配不区分大小写的确切名称,并且如果不是完全匹配则不捕获

这是我目前得到的。

$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,我发现了一些示例,但也许有一个更简单的解决方案。

【问题讨论】:

  • 但是你的代码工作正常检查它phpize.online/…
  • 不,它再次给出“我的名字是 ****tina,这是另一个例子”,刚刚检查了您的链接。

标签: php regex preg-replace str-replace


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2016-02-08
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多