【问题标题】:i want extract matched words from string and return it including 2 words before it and 2 words after it (if found)我想从字符串中提取匹配的单词并返回它,包括它之前的 2 个单词和之后的 2 个单词(如果找到)
【发布时间】:2012-12-18 07:37:04
【问题描述】:

我想做一个大多数搜索引擎似乎都在做的把戏。

假设我有这个字符串:

$str = "Hello Mr. Ben From the UK, nice to meet you";

我想要一个正则表达式来搜索两个或多个单词,本例中的单词是toBen

我可以使用 preg_match_all 做到这一点

preg_match_all("#[\w+]*(to|Ben)+\w*#isx", $str,$matches);

它工作正常,但我需要返回每个短语中匹配的单词。 例如单词to,我想返回匹配这种格式nice tomeet,即包裹在周围的单词中

我想为 Ben 做同样的事情,

我可以使用explodepreg_matchloop 来做到这一点,所以我认为最好使用preg_match_all

PS:我还有一个小问题,我可以做这个“技巧”,但在从我的数据库中获取数据时使用sql query

谢谢。

【问题讨论】:

标签: php mysql sql full-text-search preg-match-all


【解决方案1】:

我是通过这个正则表达式做到的

preg_match_all("#(.){0,15}(to|Ben)+(.){0,15}#isx", $str,$matches, PREG_PATTERN_ORDER , 1);
var_dump($matches);

为大家分享答案

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-13
    • 2015-04-08
    • 2021-10-14
    相关资源
    最近更新 更多