drdzpknk76046 2013-07-23 16:20
浏览 43
已采纳

PHP Regex关键词匹配

I have a text field where the user will enter comma separated keywords or key phrases, and the server will then use these values to check multiple bodies of text for matches.

So basically what I need is to match an exact phrase, case insensitive, with possible spaces in a body of text.

I can match keywords easily, by generating the following regex:

Example keywords: peanut, butter, jelly

Regex generated: /peanut|butter|jelly/i

However having spaces does not work. Even if I replace the spaces in the given values with \s

Example: peanut butter, jelly sandwich, delicious

Regex: /peanut\sbutter|jelly\ssandwich|delicious/i

What would be a correct regex to match the phrases exactly ? Case insensitive and using PHP's preg_match ?

Thanks.

EDIT

This is what I am doing:

$keywordsArray = array_map( 'trim', explode( ',', $keywords ) );
$keywordsArrayEscaped = array_map( 'preg_quote', $keywordsArray );
$keywordsRegex = '/' . implode( '|', $keywordsArrayEscaped ) . '/i';

The above generates the expressions as described above ( Without the replacement of spaces to \s, since it didn't work. )

Following that I simple do preg_match( $keywordsRegex, $text );

  • 写回答

2条回答 默认 最新

  • dongzhang7961 2013-07-23 16:31
    关注

    I don't see why it wouldn't work with spaces or \s. It should. But to answer the question you asked in general terms, the way to match exact phrases in a regex is to surround them with \Q and \E:

    /\Q<phrase 1>\E|\Q<phrase 2>\E|\Q<phrase 3>\E/
    

    That's normally used for text that contains escapes or regex metacharacters. You really shouldn't need that for spaces.

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

报告相同问题?

悬赏问题

  • ¥15 应该如何判断含间隙的曲柄摇杆机构,轴与轴承是否发生了碰撞?
  • ¥15 vue3+express部署到nginx
  • ¥20 搭建pt1000三线制高精度测温电路
  • ¥15 使用Jdk8自带的算法,和Jdk11自带的加密结果会一样吗,不一样的话有什么解决方案,Jdk不能升级的情况
  • ¥15 画两个图 python或R
  • ¥15 在线请求openmv与pixhawk 实现实时目标跟踪的具体通讯方法
  • ¥15 八路抢答器设计出现故障
  • ¥15 opencv 无法读取视频
  • ¥15 按键修改电子时钟,C51单片机
  • ¥60 Java中实现如何实现张量类,并用于图像处理(不运用其他科学计算库和图像处理库))