下面是零宽断言的几个例子:
$str = 'by ttabdef';
//1、(?:exp) 匹配exp但是不捕获
preg_match('/(?:ab)def/', $str, $match1);/*array([0] => abdef)*/
//2、(?=exp)断言自身出现的位置的后面能匹配表达式exp
$str1 = 'dancing';
preg_match('/\w+(?=ing)/', $str1, $t1);//array([0] => danc)
preg_match('/tt(?=ab)ab/', $str, $match2);//Array([0] => ttab)
//3、(?<=exp)断言自身出现位置的前面能匹配正则表达式, js不支持该写法
preg_match('/(?<=ab)def/', $str, $match3);//array([0] => def)
preg_match('/(?<=c)def/', $str, $t2);//array()
//4、(?!exp)断言自身出现位置的后面不能匹配正则表达式
preg_match('/tt(?!c)/', $str, $match4);//array([0] => tt)
//5、(?<!exp)断言自身出现位置的前面不能匹配正则表达式, js不支持该写法
preg_match('/(?<!c)def/', $str, $t3);//array([0] => def)
在提数时会遇到这种情况:
原sql中:keyword != "http://css.cn.msn.com/msntoday/default.html" and
keyword != "http://css.cn.msn.com/msntoday/dictoday/default.shtml" and
keyword != "http://css.cn.msn.com/msntoday/default_dict.html"
正则写的话,就用到负向零宽断言,如下:
$regex = '/(?<!css.cn.msn.com/msntoday/(default|dictoday/default|default_dict)\\.[s]?html$/i'
但是有一点需要注意, 逆序环视只能匹配固定长度的文本 。不可以使用 (?<=books?) 、 (?<=\w+) 或 (?=\d{2,3})
提数时也会遇到如下情况:
1
原sql中:(keyword like "%.html" or keyword like "%.shtml") and (keyword NOT LIKE "%.ynet.com%")
但是不能用如下正则:
$regex = '/(?<!ynet.com).*[s]?html/i'