php url正则表达式
本文章收集了三种关于从字符串或文章内容中匹配url正则表达式的php代码,前二种函数是获取以域名为标题的http,后一种是匹配内容中的url地址并且保存到数组中.
- //方法一
- $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
- $pattern = $ereg_str['url'];
- if(ereg($pattern,$string)) echo " <br> right! ";
- else echo " <br> error! ";
- }
- //方法二
- $str[] = "http://www.phpfensi.com";
- $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 ';
- foreach($str as $key=> $val)
- {
- $key++;
- if(preg_match($pattern,$val))
- echo " <br> <font color=green> right! </font> ".$val;
- else
- echo " <br> <font color=red> error! </font> ".$val;
- }
- //方法三
- //匹配<a href="xxxxxx">yyyyyy</a>
- "/<a.+hrefs*=s*['"]?([^s<'"]*)['"]?.*>([^</a>].*)</a>/i"
- //匹配href="xxxxxx"
- s*<[aa]{1}s*href="([^"]*)"s*>([^<]*)</1>
- $reg = "<a[ss]*?(href)s*=s*(?(?=["'])((["'])(?<href>[^"']*)2)|(?<src>[^s>]+))[ss]*?>";
- ?>