我正在嘗試替換逗號分隔列表中的名稱。但是,無法弄清楚如何匹配確切的名稱,不區分大小寫,并且如果不完全匹配則不捕獲這是我到目前為止所得到的。$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條經驗 獲得超3個贊
嘗試使用值中的 \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 中使用單詞邊界,但如果需要,可以輕松添加。
- 1 回答
- 0 關注
- 139 瀏覽
添加回答
舉報
0/150
提交
取消