douli2876 2013-11-25 03:08
浏览 37
已采纳

PHP preg_replace:匹配包含短划线的单词

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 "-" ?

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

Thank you very much for your help !

  • 写回答

1条回答 默认 最新

  • douwen1929 2013-11-25 03:14
    关注
    $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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部