php正则应用:异常Delimiter must not be alphanumeric or backslash

来源:互联网 发布:北海旅游 知乎 编辑:程序博客网 时间:2024/04/25 14:38

咳咳,三年多不用php了,很多东西都忘记了,为了全栈,现在一点点拾起来,同时写下博客记录曾经走过的坑和现在正在走的坑。

出现问题的代码如下:

$content = request("http://pp.163.com/pp/searchpic/?q=%B7%E7%BE%B0");$details = matchDetailInList($content);var_dump($details);function request($url) {    $ch = curl_init($url);    curl_setopt($ch, CURLOPT_HEADER, false);    curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);//返回字符串而不是直接输出    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); // 页面发生301,302跳转    $result = curl_exec($ch);    curl_close($ch);    return $result;}/** * 匹配列表页面中的详情页面地址 */function matchDetailInList($content) {    //注意,这个在php中有问题    $ruleMatchDetailInList = "http://*[^\"]*\.html[^\"]*";    preg_match_all($ruleMatchDetailInList,$content,$result);      return $result;  }

此代码执行时,出现以下异常:

Warning: preg_match_all(): Delimiter must not be alphanumeric or backslash in D:\wamp\www\curl\curlTest.php on line 29

在正则测试工具中完全没问题的,在php中出问题什么鬼?

看Warning中提示,可以看到是在说定界符不能是字母数字或反斜线。

定界符什么东西?这个是在preg中才有的,ereg中是没有的,这个定界符划定了正则表达式的开始和结尾。那就在前后两边加上定界符试试吧,既然说不能用字母数字或反斜线,那就用其他字符,比如#、~、/(当然,前后必须成双成对出现)

首先换成了#或者~

function matchDetailInList($content) {    $ruleMatchDetailInList = "~http://*[^\"]*\.html[^\"]*~";    preg_match_all($ruleMatchDetailInList,$content,$result);      return $result;  }

果然成功,如下图
这里写图片描述

但是,当换成/斜线的时候

function matchDetailInList($content) {    $ruleMatchDetailInList = "/http://*[^\"]*\.html[^\"]*/";    preg_match_all($ruleMatchDetailInList,$content,$result);      return $result;  }

又报错了。。。

Warning: preg_match_all(): Unknown modifier '/' in D:\wamp\www\curl\curlTest.php on line 29

如下图:
这里写图片描述

未知修饰符’/’?还是正则中有问题!
这是由于正则中本身就有’/’,看“http://”中的两个’//’,跟定界符发生冲突了,加上反斜线,转义一下试试

function matchDetailInList($content) {    $ruleMatchDetailInList = "/http:\/\/*[^\"]*\.html[^\"]*/";    preg_match_all($ruleMatchDetailInList,$content,$result);      return $result;  }

运行一下
这里写图片描述

果然没问题了!
所以,建议大家定界符使用的时候,尽量避免使用斜线/,避免和正则中的斜线冲突。

总结:
1、在php中,要有定界符
2、定界符尽量不要使用斜线/,而是使用#或者~

0 0
原创粉丝点击