2016-11-13 81 views
0

这里是我的代码:当我们有一个子字符串时如何匹配整个单词?

$txt = 'this is a text'; 
$word = 'is'; 
echo str_replace($word, '<b>'.$word.'</b>', $txt); 
//=> th<b>is</b> <b>is</b> a text 

正如你看到的,我的子字符串是上面的例子中is,它只是isthis部分匹配。虽然我需要选择整个单词。因此,这是预期的结果:

//=> <b>this</b> <b>is</b> a text 

所以我需要检查子串的左侧和右侧,符合一切,直到第一个字符串^或字符串$或白色S页面\s月底。

我该怎么做?

+0

那么你可以用String#的indexOf,然后知道使用适当子建的包装。 – Rogue

回答

0

使用正则表达式与word boundary anchors

$regex = '/\b(\p{L}*' . preg_quote($word, '/') . '\p{L}*)\b/u'; 
echo preg_replace($regex, '<b>$1</b>', $txt); 

其中\p{L}代表一个Unicode信(见Unicode character classes)。例如,如果Unicode不受支持,请将\p{L}替换为\S(非空格字符)。

输出

<b>this</b> <b>is</b> a text 
0

如果你想匹配一个单词的字符串,以及这个词本身就可以检查单词周围的任何单词字符,你寻找像这样:

$re = '/(\w*is\w*)/'; 
$str = 'this is a text'; 
$subst = '<b>$1<b>'; 

$result = preg_replace($re, $subst, $str); 

echo "The result of the substitution is ".$result; 

这会给你:

<b>this<b> <b>is<b> a text 
相关问题