search
Homephp教程PHP开发A simple way to match URLs with regular expressions in php

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


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

测试代码如下:

<?php
$search = &#39;~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i&#39;;
$url = &#39;http://www.jb51.net/pub/ietf/uri/#Gonn&#39;;
$url = trim($url);
preg_match_all($search, $url ,$rr);
printf("<p>输出URL数据为:</p><pre class="brush:php;toolbar:false">%s
\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中的任何一部分,下面的代码则简单一些:

<?php 
// 从 URL 中取得主机名 
preg_match("/^(http:\/\/)?([^\/]+)/i", "http://www.jb51.net/index.html", $matches); 
$host = $matches[2]; 
// 从主机名中取得后面两段 
preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches); 
echo "domain name is: {$matches[0]}\n"; 
?>


Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor