提取字符串中给定搜索字符串周围的X个字

pro*_*guy 7 php regex mysql search

我正在寻找一种方法来在搜索中的给定单词的两侧提取X个单词.

例如,如果用户输入"inmate"作为搜索词并且MySQL查询在帖子的内容中找到包含"inmate"的帖子,我想不返回帖子的全部内容而只返回x个在它的任何一侧的文字给用户的帖子的要点,然后他们可以决定他们是否想继续到帖子并完整阅读.

我正在使用PHP.

谢谢!

mor*_*rja 9

您可能无法使用正则表达式完全解决此问题.单词之间有太多其他字符的可能性......

但你可以尝试这个正则表达式:

((?:\S+\s*){0,5}\S*inmate\S*(?:\s*\S+){0,5})
Run Code Online (Sandbox Code Playgroud)

见这里:rubular

您可能还想排除某些字符,因为它们不算作单词.现在,正则表达式将任何由空格包围的非空格字符序列计为单词.

仅匹配真实的单词:

((?:\w+\s*){0,5}<search word>(?:\s*\w+){0,5})
Run Code Online (Sandbox Code Playgroud)

但是这里任何非单词字符(,".等)都会对匹配进行制动.

所以你可以继续......

((?:[\w"',.-]+\s*){0,5}["',.-]?<search word>["',.-]?(?:\s*[\w"',.-]+){0,5})
Run Code Online (Sandbox Code Playgroud)

这也可以在搜索字词周围匹配5个单词和"',.-之一.

要在php中使用它:

$sourcestring="For example, if a user enters \"inmate\" as a search word and the MySQL";
preg_match_all('/(?:\S+\s*){0,5}\S*inmate\S*(?:\s*\S+){0,5}/s',$sourcestring,$matches);
echo $matches[0][0]; // you might have more matches, they will be in $matches[0][x]
Run Code Online (Sandbox Code Playgroud)