Php 捕获无约束的重复模式
我希望能够查看字符串并找到所有出现的模式。如果您知道模式将出现多少次,那么使用preg_match很容易做到这一点,但如果出现的次数未知,我无法找到一种方法来实现这一点 以下是已知事件集的工作查询示例:Php 捕获无约束的重复模式,php,Php,我希望能够查看字符串并找到所有出现的模式。如果您知道模式将出现多少次,那么使用preg_match很容易做到这一点,但如果出现的次数未知,我无法找到一种方法来实现这一点 以下是已知事件集的工作查询示例: $pattern = '/\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\]/'; $string = "[VAR:one] once apon a time [VAR:two]. And then there was the time
$pattern = '/\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\].*\[VAR:(.*)\]/';
$string = "[VAR:one] once apon a time [VAR:two]. And then there was the time that [VAR:three] went to [VAR:four]";
preg_match ( $pattern , $string, $matches );
print_r ( $matches );
这将返回您期望的结果:
[0] => [VAR:one] once apon a time [VAR:two]. And then there was the time that [VAR:three] went to [VAR:four]
[1] => one
[2] => two
[3] => three
[4] => four
我尝试了使用模式的preg\u match和preg\u match\u all变体(使用和不使用preg\u OFFSET\u捕获参数),但均未成功:
任何帮助都将不胜感激。以下模式和
preg\u match\u all
$pattern = "/\[VAR:(.*?)\]/";
有关修改后的示例,请参见
*
之后的?
使其不贪婪
$pattern = "/\[VAR:(.*?)\]/";