Home > Backend Development > PHP Tutorial > php用正则表达式匹配URL的简单方法_php实例

php用正则表达式匹配URL的简单方法_php实例

WBOY
Release: 2016-06-07 17:23:04
Original
1436 people have browsed it

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

复制代码 代码如下:

^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?
12            3  4       

测试代码如下:
复制代码 代码如下:

$search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';
$url = 'http://www.php.net/pub/ietf/uri/#Gonn';
$url = trim($url);
preg_match_all($search, $url ,$rr);
printf("

输出URL数据为:

%s
Copy after login
\n",var_export( $rr ,TRUE));

/*
各分组如下
      $1 = http:
      $2 = http
      $3 = //www.nowamagic.net
      $4 = www.nowamagic.net
      $5 = /pub/ietf/uri/
      $6 =
      $7 =
      $8 = #Gonn
      $9 = Gonn
*/
?>


上面的正则表达式可以获取URL中的任何一部分,下面的代码则简单一些:
复制代码 代码如下:

// 从 URL 中取得主机名
preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.php.net/index.html", $matches);
$host = $matches[2];
// 从主机名中取得后面两段
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
echo "domain name is: {$matches[0]}\n";
?>
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template