简体   繁体   中英

PHP: How to get all regular expression matches?

Is it possible to get all regular expression matches in PHP? I need a script that will, for example, match .+ in abc and give the result:

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

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. 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').

And the following will split pairs of characters with the remaining single character:

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

Giving you: 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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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