首页 | PHP资讯 | 技术专栏 | 资源共享 | PHP培训 | PHP职场 | 图书 | PHP ON WIN | PHP圈子 | PHPer学习大本营
返回列表 回复 发帖

一个正则求助

已解决

一个正则求助

悬赏金额: 1 开源币

有一个提取链 接的正则

  1. preg_match_all("'<\s*a\s.*?href\s*=\s*([\"\'])?(?(1)(.*?)\\1|([^\s\>]+))[^>]*>?(.*?)</a>'isx",$document,$links);
复制代码

对于一般的规范链 接能很好的使用,但不知道为什么对href=后面的网址不含引号的情况无法提取成功,哪个朋友帮分析下?谢谢!

最佳答案 CFC4N
分析见这里。如有不当,请斧正。
http://www.cnxct.com/snoopy-clas ... %E5%88%86%E6%9E%90/

分析见这里。如有不当,请斧正。
http://www.cnxct.com/snoopy-clas ... %E5%88%86%E6%9E%90/
http://www.cnxct.com/

TOP

此正则写得太死
龇牙咧嘴的白菜
http://aiyooyoo.com

TOP

本帖最后由 落叶人生 于 2010-7-25 13:17 编辑
此正则写得太死
那个故事 发表于 2010-7-25 13:04



    此正则修改于Snoopy.class.php中的_striplinks
原函数:

  1. function _striplinks($document)
  2. {
  3.   preg_match_all("'<\s*a\s.*?href\s*=\s*   # find <a href=
  4.       ([\"\'])?     # find single or double quote
  5.       (?(1) (.*?)\\1 | ([^\s\>]+))  # if quote found, match up to next matching
  6.              # quote, otherwise match up to next space
  7.       'isx",$document,$links);
  8.       
  9.   // catenate the non-empty matches from the conditional subpattern
  10.   while(list($key,$val) = each($links[2]))
  11.   {
  12.    if(!empty($val))
  13.     $match[] = $val;
  14.   }   
  15.   
  16.   while(list($key,$val) = each($links[3]))
  17.   {
  18.    if(!empty($val))
  19.     $match[] = $val;
  20.   }  
  21.   
  22.   // return the links
  23.   return $match;
  24. }
复制代码

TOP

回复 4# CFC4N


    非常感谢,但是我用

  1. preg_match_all("'<\s*a\s.*?href\s*=\s*([\"\'])?(?(1)(.*?)\\1|([^\s\>]+))[^>]*>?(.*?)</a>'isx",'<a href=a.htm>fffffffff</a> <a href="dfssdfsgshttp://www.baidu.com">dfssdfsgs</a> <a href="c">ededsfa</a>',$links);
复制代码

第一个链接a.htm并不能匹配到

TOP

回复 5# 落叶人生


    是可以匹配到的,print_r($links[0]);可知 。可能你需要的是href部分,有引号时它分开两个数组返回,$links[2]是无 a.htm 的,在$links[3]。删掉里面的“?(1)”,不作条件判断即可。

  1. preg_match_all("'<\s*a\s.*?href\s*=\s*([\"\'])?((.*?)\\1|([^\s\>]+))[^>]*>?(.*?)</a>'isx",'<a href=a.htm>fffffffff</a> <a href="dfssdfsgshttp://www.baidu.com">dfssdfsgs</a> <a href="c">ededsfa</a>',$links);  
  2. print_r($links[2]);
复制代码

TOP

回复 6# www333


    哦,可以这样解决啊,呵呵,非常感谢,我昨天通过将$link[3]与$link[2]合并解决了,作了个循环,可以效率稍低些

TOP

返回列表