实例 3-29 从URL 中取出域名
本实例演示了如何从URL 中取出域名,如代码3-29 所示。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
  <head>
   <title> preg_match_3.php </title>
   <meta charset="UTF-8">
   <meta name="Author" content="">
   <meta name="Keywords" content="">
   <meta name="Description" content="">
  </head> <body>
<?php
 // 从 URL 中取得主机名
 preg_match("/^(http:\/\/)?([^\/]+)/i",
 "http://www.php.net/index.html", $matches);
 //获取主机名
 $host = $matches[2];
 // 从主机名中取得后面两段得到域名
 preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
 echo "域名为: {$matches[0]}\n";
 ?>
  </body>
 </html>


域名为: php.net

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 <html>
  <head>
   <title> preg_match_3.php </title>
   <meta charset="UTF-8">
   <meta name="Author" content="">
   <meta name="Keywords" content="">
   <meta name="Description" content="">
  </head> <body>
<?php
 // 从 URL 中取得主机名
 preg_match("/^(http:\/\/)?([^\/]+)/i",
 "http://www.php.net/index.html", $matches);
 var_dump($matches);
 //获取主机名
 $host = $matches[2];
 var_dump($host);
 // 从主机名中取得后面两段得到域名
 preg_match("/[^\.\/]+\.[^\.\/]+$/", $host, $matches);
 var_dump($matches);
 echo "域名为: {$matches[0]}\n";
 ?>
  </body>
 </html>
 array
   0 => string 'http://www.php.net' (length=18)
   1 => string 'http://' (length=7)
   2 => string 'www.php.net' (length=11)string 'www.php.net' (length=11)
array
   0 => string 'php.net' (length=7)

域名为: php.net