URL 一个通用资源标志符(Uniform Resource Identifier, 简称"URI")进行定位。
对象分组:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?
12 3 4 5 6 7 8 9
例1,
<?php
$search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?~i';
$url = 'http://www.jb200.com/pub/ietf/uri/#Gonn';
$url = trim($url);
preg_match_all($search, $url ,$rr);
printf("<p>输出URL数据为:</p><pre>%s</pre>n",var_export( $rr ,TRUE));
/*
各分组如下
$1 = http:
$2 = http
$3 = //www.jb200.com
$4 = www.jb200.com
$5 = /pub/ietf/uri/
$6 = <undefined>
$7 = <undefined>
$8 = #Gonn
$9 = Gonn
*/
?>
以上的正则表达式可以获取URL中的任何一部分。
下面这段代码更简洁,易懂一些。
<?php
// 从 URL 中取得主机名
preg_match("/^(http://)?([^/]+)/i", "http://www.jb200.com/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^./]+.[^./]+$/", $host, $matches);
echo "domain name is: {$matches[0]}n";
?>
您可能感兴趣的文章:
php匹配图片地址的代码一例
PHP正则匹配日期和时间(时间戳转换)的例子
php匹配任何网址的正则表达式
php正则匹配重写html图片img路径的代码一例
使用 preg_replace 函数 匹配图片并加上链接的方法
php用preg_match_all匹配文章中的图片
php正则表达式匹配URL中的域名