PHP正则 贪婪形式与懒惰模式

WBOY
Release: 2016-06-13 13:14:02
Original
781 people have browsed it

PHP正则 贪婪模式与懒惰模式
贪婪模式
当正则表达式中包含能接受重复的限定符时,通常的行为是(在使整个表达式能得到匹配的前提下)匹配尽可能多的字符。
考虑这个表达式:a.*b,它将会匹配最长的以a开始,以b结束的字符串。如果用它来搜索aabab的话,它会匹配整个字符串aabab。这被称为贪婪匹配。

懒惰模式
有时,我们更需要懒惰匹配,也就是匹配尽可能少的字符。前面给出的限定符都可以被转化为懒惰匹配模式,只要在它后面加上一个问号?。这样.*?就意味着匹配任意数量的重复,但是在能使整个匹配成功的前提下使用最少的重复。现在看看懒惰版的例子吧:

a.*?b匹配最短的,以a开始,以b结束的字符串。如果把它应用于aabab的话,它会匹配aab(第一到第三个字符)和ab(第四到第五个字符)。

例子2
要求字符串: src="http://www.bloghome.cn/1.mp3" type="application/x-mplayer2" 中找到匹配结果:http://www.bloghome.cn/1.mp3

如果匹配表达式写为:/src="(.*)"/

$str ='src="http://www.bloghome.cn/1.mp3" type="application/x-mplayer2"'; 
preg_match('/src="(.*)"/', $str, $matches);
Copy after login

得到$matches[1]结果为http://www.bloghome.cn/1.mp3" type="application/x-mplayer2因为最后一个双引号的匹配是贪婪模式的。

如果匹配表达式写为:/src="(.*?)"/,得到$matches[1]结果为http://www.bloghome.cn/1.mp3

结尾定界符/后面的含义
注意, 若pattern中使用了

引用
/i 表示不区分大小写
/s 表示.还匹配空白字符
/U 表示模式反转, 即贪婪匹配模式变成懒惰匹配模式, 懒惰匹配模式变成贪婪匹配模式

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!