简体   繁体   English

PHP:如何获取所有正则表达式匹配项?

[英]PHP: How to get all regular expression matches?

Is it possible to get all regular expression matches in PHP? 是否有可能在PHP中获得所有正则表达式匹配项? I need a script that will, for example, match .+ in abc and give the result: 我需要一个脚本,例如,匹配abc中的.+并给出结果:

Array( a , b , c , ab , bc , abc ) Array( abcabbcabc

The issue is at the overlap, you want to match 'ab' and also 'bc' which you won't be able to do with a simple regex. 问题是重叠的,您想匹配“ ab”和“ bc”,而这是简单正则表达式无法实现的。 However consider the following. 但是请考虑以下内容。

You can split out every character with either of these lines: 您可以使用以下任一行拆分每个字符:

preg_match_all('/./', 'abc', $matches);
str_split('abc');

Giving you: array('a', 'b', 'c'). 给你:array('a','b','c')。

And the following will split pairs of characters with the remaining single character: 下面将用剩下的单个字符分割成对的字符:

preg_match_all('/.{2}|./', 'abc', $matches);

Giving you: array('ab', 'c'); 给你:array('ab','c');

So you could play around with combinations/variations of these to achieve your outcome. 因此,您可以玩弄这些的组合/变体以达到目标。

I'm not sure there is a defined set of "all matches" in a regular expression. 我不确定正则表达式中是否有一组已定义的“所有匹配项”。

For example, what if your pattern were .+.+ ? 例如,如果您的模式是.+.+怎么办? What is matched by the first .+ ? 什么是第一个.+匹配的? What is matched by the second? 第二个是什么?

A string may match a particular RE binding in multiple different ways, and which substring is captured by different parts of the RE may depend on things like greedy vs. non-greedy matching. 字符串可以以多种不同方式匹配特定的RE绑定,并且RE的不同部分捕获的子字符串可能取决于贪婪与非贪婪匹配。 But there is no defined way to iterate over all the different possible captures. 但是没有定义的方法可以迭代所有可能的捕获。 You'd have to dramatically change the way that REs are processed to do this. 您必须极大地改变RE的处理方式。

I know the question is a bit old, but there still might be someone who needs the answer. 我知道这个问题有点老了,但仍然可能有人需要答案。

Look at the flags parameter for preg_match_all function 查看preg_match_all函数的flags参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM