douzhan2027 2014-07-27 09:12
浏览 37
已采纳

PHP中字符串中的粗体匹配文本

I use the following code for replacing matched words within a String:

  1. for ($i=0; $i < count($terms); $i++) {
  2. if ( $terms[$i] == '' || $terms[$i] == ' ' || strlen($terms[$i])==0 ) continue;
  3. $searchingFor = "/" . $terms[$i] . "/i";
  4. $replacePattern = "<strong>$0</strong>";
  5. $result['titulo'] = preg_replace($searchingFor, $replacePattern, $result['title']);
  6. }
  7. echo $result['title'];

Where 'terms' is an Array from $_GET['terms'].

All works fine except when user input strings containing characters like slashes. It arise an exception in preg_replace.

How can i solve this issue?

Thanks.

  • 写回答

2条回答 默认 最新

  • dongyi7513 2014-07-27 09:22
    关注

    Use preg_quote:

    $searchingFor     = "/" . preg_quote($terms[$i], "/") . "/i";
    

    This function puts a backslash \ before all characters used in preg syntax (. \ + * ? [ ^ ] $ ( ) { } = ! < > | : -) and also before all characters in the second argument, used here to escape your delimiter character /.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)
编辑
预览

报告相同问题?

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

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

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

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

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

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

客服 返回
顶部