Non greedy pattern matching in PHP regular expressions

Time:2021-12-25

In general, the matching of regular expressions is greedy. For example, the following example:

String: src=” http://www.bloghome.cn/1.mp3 ” type=”application/x-mplayer2″ ….
Required results: http://www.bloghome.cn/1.mp3

If the matching expression is written as: / SRC = “(. *)” /, you will not get the correct result because the matching of the last double quotation mark is greedy.

Solution: write the matching expression as:
/src=”(.*)”.?/

In the above expression, “.? is a non greedy pattern matching. That is, as long as a character is followed by a specified number of special characters, the matching is a non greedy pattern.

Recommended Today

Batch file rename tool

explain Recently, I downloaded some materials on the Internet, and all the file names were added with website related information, resulting in very long file names Besides, I don’t like it either Then, it is necessary to modify the file name again. There are still many files, which is really inconvenient to modify manually So […]