I am facing a problem searching words in a string and converting them into links. How to make a search that considers words containing a "-" as whole word and not as 2 words separated by "-" ?
我在搜索字符串中的单词并将其转换为链接时遇到问题。如何进行搜索,将包含“ - ”的单词视为整个单词,而不是将“ - ”分隔为2个单词?
Here is an example, if I search for the word "exhaustive", my search function will also match the part of the word "non-exhaustive", although i don't want this word to be matched.
这是一个例子,如果我搜索“穷举”这个词,我的搜索功能也会匹配“非详尽”这个词的部分,虽然我不希望这个词匹配。
$string = "Bla bla bla non-exhaustive blabla bla exhaustive";
$words = array('exhaustive','non-exhaustive');
foreach ($words as $word) {
$string = preg_replace('/\b'.$word.'\b/i', '<a href=#>'.$word.'</a>',$string);
}
echo $string;
Result :
Bla bla bla non-exhaustive blabla bla exhaustive
Bla bla bla非详尽的blabla bla详尽无遗
Thank you very much for your help !
非常感谢您的帮助 !
1 个解决方案
#1
1
$string = preg_replace('/\b[^\-]' . preg_quote($word) . '\b/i', '<a href=#>' . $word . '</a>',$string);
Should do the trick :)
应该做的伎俩:)
*edit, Aleks did beat me with just 2 sec :p
*编辑,亚历克斯只用2秒击败了我:p
#1
1
$string = preg_replace('/\b[^\-]' . preg_quote($word) . '\b/i', '<a href=#>' . $word . '</a>',$string);
Should do the trick :)
应该做的伎俩:)
*edit, Aleks did beat me with just 2 sec :p
*编辑,亚历克斯只用2秒击败了我:p