您可能无法使用正则表达式完全解决此问题。单词之间有太多其他字符的可能性...
但是你可以试试这个正则表达式:
((?:\S+\s*){0,5}\S*inmate\S*(?:\s*\S+){0,5})
请看这里:rubular
您可能还想排除某些字符,因为它们不计为单词。现在正则表达式将任何被空格包围的非空格字符序列计算为单词。
只匹配真实的单词:
((?:\w+\s*){0,5}<search word>(?:\s*\w+){0,5})
但是这里任何非单词字符(,,,等等)都会阻止匹配。
所以你可以继续...
((?:[\w"',.-]+\s*){0,5}["',.-]?<search word>["',.-]?(?:\s*[\w"',.-]+){0,5})
这也将匹配 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]