我有一個單詞和一個字符串數組,並希望添加一個hashtag字符串中的單詞,他們有一個匹配的數組內。我用這個循環來查找和替換的話:preg替換會忽略非字母字符時檢測到的單詞
foreach($testArray as $tag){
$str = preg_replace("~\b".$tag."~i","#\$0",$str);
}
問題:可以說我有詞「是」,並在我的數組「隔離」。我將在輸出處得到##隔離。這意味着「孤立」這個詞在「is」中找到一次,在「isolate」中找到一次。並且該模式忽略了「#isoldated」不再以「is」開頭並以「#」開頭的事實。
我帶來了一個例子,但這只是爲例 e和我不希望只是解決這一之一,但所有其他方法可行:
$str = "this is isolated is an example of this and that";
$testArray = array('is','isolated','somethingElse');
輸出將是:
this #is ##isolated #is an example of this and that