PHP正则之贪婪和非贪婪模式
PHP的正则表达式
非贪婪模式, 尽量少匹配符合条件的项目
贪婪模式, 尽量多匹配符合条件的项目
<?php
// 非贪婪模式
$a = '<h3>123123123</h3><h3 class="h3Title">abcdef</h3>123123123<div></div><h3></h3><h3 class="h3Title"><p>goodboy<p></h3>';
$pattern = '/<h3 class="h3Title">(?:.|\n)*?<\/h3>/';
$b = preg_match_all($pattern, $a, $arr);
var_dump($arr);
/*
output:
array(1) {
[0]=>
array(2) {
[0]=>
string(31) "<h3 class="h3Title">abcdef</h3>"
[1]=>
string(38) "<h3 class="h3Title"><p>goodboy<p></h3>"
}
}
*/
正则替换:
非贪婪模式:
<?php $str = 'remove a tag:<a href="index.php">hello world</a>kim green!<a href="sina.com"> goodstudy</a>'; $pattern = '/\<a (.*?)\>(.*?)\<\/a\>/'; $str = preg_replace($pattern, '$2', $str); var_dump($str); /* output: remove a tag:hello worldkim green! goodstudy */ ?>
参考资料:
http://hi.baidu.com/seanaq/blog/item/fb34e87ee49ae63e0cd7da2c.html
-------------我的签名档---------------------
年轻人,还需要多努力!
--------------------------------------------