php url正则表达式

本文章收集了三种关于从字符串或文章内容中匹配url正则表达式的php代码,前二种函数是获取以域名为标题的http,后一种是匹配内容中的url地址并且保存到数组中.

  1. //方法一
  2. $ereg_str[url] = "^[hh]{1}[tt]{2}[pp]{1}://[ww]{3}.[0-9a-za-z][0-9a-za-z-]{0,25}((.[a-za-z]{3,4})|(.[a-za-z]{2})){1,2}$ "; //判断一个合法的url
  3. $pattern = $ereg_str['url'];
  4. if(ereg($pattern,$string)) echo " <br> right! ";
  5. else echo " <br> error! ";
  6. }
  7. //方法二
  8. $str[] = "http://www.phpfensi.com";
  9. $pattern = '/^(http://)?www.[0-9a-z][0-9a-z-]{0,25}((.(aero|biz|cc|co|com|coop|edu|gov|info|int|mil|museum|name|nato|net|org|tv))?(.(af|aq|at|au|be|bg|br|ca|ch|cl|cn|de|eg|es|fi|fr|gr|hk|hu|ie|il|in|iq|ir|is|it|jp|kr|mx|nl|no|nz|pe|ph|pr|pt|ru|se|sg|th|tr|tw|uk|us|za))?){1}$/i ';
  10. foreach($str as $key=> $val)
  11. {
  12. $key++;
  13. if(preg_match($pattern,$val))
  14. echo " <br> <font color=green> right! </font>   ".$val;
  15. else
  16. echo " <br> <font color=red> error! </font>   ".$val;
  17. }
  18. //方法三
  19. //匹配<a href="xxxxxx">yyyyyy</a>
  20. "/<a.+hrefs*=s*['"]?([^s<'"]*)['"]?.*>([^</a>].*)</a>/i"
  21. //匹配href="xxxxxx"
  22. s*<[aa]{1}s*href="([^"]*)"s*>([^<]*)</1>
  23. $reg = "<a[ss]*?(href)s*=s*(?(?=["'])((["'])(?<href>[^"']*)2)|(?<src>[^s>]+))[ss]*?>";
  24. ?>