簡體   English   中英

替換作為逗號分隔列表一部分的字符串中的值。 PHP

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM