Preg Match之前和之后的单词和句点

时间:2013-07-19 20:43:47

标签: php regex preg-match

我有一个preg匹配工作来查找单词title或loan的所有实例,但是任何人都可以帮我修改它以获取单词的所有实例,加上之前和之后的所有单词。作为停止的分隔符。

preg_match_all('#\b(title|loan)\b#',$html, $matches);

或者说之前的10个单词和im之后的10个单词。

谢谢

1 个答案:

答案 0 :(得分:1)

preg_match_all('#(?<pre>\w+) (title|loan) (?<post>\w+)#',$html, $matches);

将捕获title|loan之前和之后的单词,如果它们用空格分隔。如果您的单词之间需要更灵活的界限,则可以轻松调整。

然后您可以通过以下方式访问匹配项:

foreach ($matches as $match)
{
  echo $match['pre'];
  echo $match['post'];
}

要匹配包含title|loan的句点(句子)之间的所有内容,您可以执行以下操作:

preg_match_all('#[^.]*(title|loan)[^.]*#', $html, $matches);

这将匹配title|loan之前和之后不是句点的所有字符。

相关问题