我有一个单词和一个字符串数组,并希望添加一个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