<?php
//注:正则 /a.+?e/ 是非贪婪模式(因为量词‘+’后面加上了‘?’),如果使用 /a.+?e/U 则变回了贪婪模式
preg_match("/a.+?e/","abcdefgabcdefgabcdefg",$out1);
preg_match_all("/a.+?e/","abcdefgabcdefgabcdefg",$out2);
var_dump($out1);
var_dump($out2);
/*
输出:
array (size=1)
0 => string 'abcde' (length=5)
array (size=1)
0 =>
array (size=3)
0 => string 'abcde' (length=5)
1 => string 'abcde' (length=5)
2 => string 'abcde' (length=5)
*/
?><?php
$str = "http://www.baidu/.com?url=www.sina.com/";
preg_match("/http:(.*)com/", $str, $matches1); //贪婪匹配
var_dump($matches1);
preg_match("/http:(.*?)com/", $str, $matches2); //非贪婪匹配(量词'*'后面跟上了'?')
var_dump($matches2);
/*
array (size=2)
0 => string 'http://www.baidu/.com?url=www.sina.com' (length=38)
1 => string '//www.baidu/.com?url=www.sina.' (length=30)
array (size=2)
0 => string 'http://www.baidu/.com' (length=21)
1 => string '//www.baidu/.' (length=13)
*/
?><?php
echo('PREG_PATTERN_ORDER');
preg_match_all("<[^>]+>(.*)</[^>]+>U",
"<b>start: </b><b>this is a test</b><b>end</b>",
$out1);
var_dump($out1);
echo('PREG_SET_ORDER');
preg_match_all("<[^>]+>(.*)</[^>]+>U",
"<b>start: </b><b>this is a test</b><b>end</b>",
$out2, PREG_SET_ORDER);
var_dump($out2);
/*
PREG_PATTERN_ORDER
array (size=2)
0 =>
array (size=3)
0 => string '<b>start: </b>' (length=14)
1 => string '<b>this is a test</b>' (length=21)
2 => string '<b>end</b>' (length=10)
1 =>
array (size=3)
0 => string 'start: ' (length=7)
1 => string 'this is a test' (length=14)
2 => string 'end' (length=3)
PREG_SET_ORDER
array (size=3)
0 =>
array (size=2)
0 => string '<b>start: </b>' (length=14)
1 => string 'start: ' (length=7)
1 =>
array (size=2)
0 => string '<b>this is a test</b>' (length=21)
1 => string 'this is a test' (length=14)
2 =>
array (size=2)
0 => string '<b>end</b>' (length=10)
1 => string 'end' (length=3)
*/
?>
PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号