我有一个长字符串,我想分析一个或多个匹配项。
每个匹配项均以名称“ John”或“ Julie”开头,在第二个匹配项“ brown”或“ red”之前有一些文本,然后在句点或匹配项的其他实例之前,在该匹配项之后有其余文本已到达。
例如,此字符串:
John likes brown cows and Julie eats red apples and tomatoes. I KNOW John hates red dates that are bruised but John likes red.
将产生这4个匹配项
John likes brown cows and
Julie eats red apples and tomatoes.
John hates red dates that are bruised but
John likes red.
我已经尝试过类似的操作,但它太贪婪了。第一场比赛符合所有条件。
(John|Julie).*?(brown|red).*[.]+
我需要在PHP中的preg_match_all()使用什么?
我需要使用先行/后备吗?
您可以对John
或Julie
或.
使用前瞻性,并且可以懒惰地停止第二个.*
使用整个字符串:
$str = 'John likes brown cows and Julie eats red apples and tomatoes. I KNOW John hates red dates that are bruised but John likes red.';
preg_match_all('/(?:John|Julie).*?(?:red|brown).*?(?=John|Julie|\.)/', $str, $matches);
print_r($matches);
输出:
Array
(
[0] => Array
(
[0] => John likes brown cows and
[1] => Julie eats red apples and tomatoes
[2] => John hates red dates that are bruised but
[3] => John likes red
)
)