php正则表达式匹配URL的小例子

发布时间:2020-06-26编辑:脚本学堂
本文介绍下,在php编程中,使用php正则表达式匹配URL地址的方法,分享几个小例子,供大家学习参考。

本节内容:
php正则表达式匹配URL

本节介绍下,使用正则表达式匹配URL的简单方法,有实例。

PHP中parse_url()函数的替代方案。结果和parse_url()函数差不多,是使用正则实现的。
URI 是 Web上可用的每种资源 - HTML文档、图像、视频片段、程序等 - 由一个通用资源标志符(Uniform Resource Identifier, 简称"URI")进行定位。

对象分组:
 

复制代码 代码示例:
^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?
12            3  4       

例子:
 

复制代码 代码示例:
<?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";
?>