Home >Backend Development >PHP Tutorial >preg_match_all regular expression greedy and non-greedy mode

preg_match_all regular expression greedy and non-greedy mode

巴扎黑
巴扎黑Original
2016-11-07 16:39:111994browse

Greedy matching: Regular expressions generally tend to match to the maximum length, which is the so-called greedy matching.

Non-greedy matching: Just match the result with as few matching characters as possible.

So, let’s put it into practice

Use the number of lines of php preg_match_all

Next we need to take out the two links in the string content

Php code

1.

2. $content='

This is obviously not what we want.

Then, as long as we add one more letter to $play_pattern, we can match the information we need

Php code

1. $play_pattern = '/

The result is

Array
(
[0] => Array
(
[0] => BD
[1] => DVD
)


[1] => Array
(
[0] => /videos /68759vod-play-id-68759-sid-0-pid-1.html
[1] => /videos/68759vod-play-id-68759-sid-0-pid-0.html
)


[2] => Array
(
[0] => BD
[1] => DVD
)


)

The difference between greedy mode and non-greedy mode is so big.

Such an error often occurs when regularizing lists in HTML. Using preg_match_all matches the entire string, but substring matching is ignored. leading to incorrect results.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn