Php preg replace在检测单词时将忽略非字母字符

Php preg replace在检测单词时将忽略非字母字符,php,regex,preg-replace,Php,Regex,Preg Replace,我有一个单词数组和一个字符串,我想给字符串中的单词添加一个hashtag,让它们在数组中匹配。我使用此循环查找并替换以下单词: foreach($testArray as $tag){ $str = preg_replace("~\b".$tag."~i","#\$0",$str); } 问题:假设我的数组中有“是”和“孤立”两个词。我将在输出端得到隔离。这意味着“隔离”一词一次用于“是”,一次用于“隔离”。该模式忽略了这样一个事实,即“#isolated”不再以“is”开头,而是以“#

我有一个单词数组和一个字符串,我想给字符串中的单词添加一个hashtag,让它们在数组中匹配。我使用此循环查找并替换以下单词:

foreach($testArray as $tag){
   $str = preg_replace("~\b".$tag."~i","#\$0",$str);
}
问题:假设我的数组中有“是”和“孤立”两个词。我将在输出端得到隔离。这意味着“隔离”一词一次用于“是”,一次用于“隔离”。该模式忽略了这样一个事实,即“#isolated”不再以“is”开头,而是以“#”开头

我举了一个例子,但这只是一个例子,我不想只解决这个问题,而是其他所有可能的问题:

$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

您可以构建一个带有交替组的正则表达式,该交替组两端都有单词边界,并在一次过程中替换所有匹配项:

$str = "this is isolated is an  example of this and that";
$testArray = array('is','isolated','somethingElse');
echo preg_replace('~\b(?:' . implode('|', $testArray) . ')\b~i', '#$0', $str);
// => this #is #isolated #is an  example of this and that

正则表达式看起来像

~\b(?:is|isolated|somethingElse)\b~
看看它


如果你想让你的方法有效,你可以在
\b
“~\b(?一种方法是将你的字符串按单词分割,并用你原来的单词数组建立一个关联数组(避免在数组中使用
):

$str=“这是孤立的,这是一个例子”;
$testArray=array('is'、'isolated'、'somethingElse');
$hash=array_flip(array_map('strtolower',$testArray));
$parts=preg_split(“~\b~”,$str);
对于($i=1;$i)
$str = "this is isolated is an example of this and that";
$testArray = array('is','isolated','somethingElse');

$hash = array_flip(array_map('strtolower', $testArray));

$parts = preg_split('~\b~', $str);

for ($i=1; $i<count($parts); $i+=2) {
    $low = strtolower($parts[$i]);
    if (isset($hash[$low])) $parts[$i-1] .= '#';
}

$result = implode('', $parts);

echo $result;