PHP regular matching code to obtain the domain name in the URL

WBOY
Release: 2016-07-25 09:00:29
Original
2433 people have browsed it
Use PHP regular expressions to get the domain name in the URL. Here are two small examples. They are simple and practical. Friends in need, come and take a look.

URL A Universal Resource Identifier (Uniform Resource Identifier, referred to as "URI") for positioning. Object grouping: ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(# (.*))? 12 3 4 5 6 7 8 9

Example 1,

<?php
 $search = '~^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?~i';
 $url = 'http://bbs.it-home.org/pub/ietf/uri/#Gonn';
 $url = trim($url);
 preg_match_all($search, $url ,$rr);
 printf("<p>输出URL数据为:</p><pre class="brush:php;toolbar:false">%s
Copy after login
n",var_export( $rr ,TRUE)); /* Each group is as follows $1 = http: $2 = http $3 = //bbs.it-home.org $4 = bbs.it-home.org $5 = /pub/ietf/uri/ $6 = $7 = $8 = #Gonn $9 = Gonn */ ?>

The above regular expression can obtain any part of the URL. The code below is more concise and easier to understand.

<?php 
 // 从 URL 中取得主机名 
 preg_match("/^(http://)?([^/]+)/i", "http://bbs.it-home.org/index.html", $matches); 
 $host = $matches[2]; 
 // 从主机名中取得后面两段 
 preg_match("/[^./]+.[^./]+$/", $host, $matches); 
 echo "domain name is: {$matches[0]}n"; 
?>
Copy after login


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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!