Home > Article > Backend Development > PHP regular matching code to obtain the domain name in the URL
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">%sn",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 = 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"; ?> |