Example of PHP implementation method for obtaining top level domain name in url address
- 2021-12-12 04:00:51
- OfStack
In this paper, the method of obtaining top-level domain name in url address by PHP is described as an example. Share it for your reference, as follows:
parse_url()
The obtained host is a multi-level domain name, such as mp. weixin. qq. com. We need to get top-level domain names when doing domain name blacklist.
Please leave a message to correct the shortcomings, thank you.
<?php
/**
* @Author: Ding Jianlong
* @Date: 2019-03-07 16:14:04
* @Last Modified by: Ding Jianlong
* @Last Modified time: 2019-03-20 13:45:12
*/
header('content-type:text/html;charset=utf-8');
// Get top-level domain name
function getTopHost($url){
$url = strtolower($url); // Turn to lowercase first
$hosts = parse_url($url);
$host = $hosts['host'];
// What level of domain name is it to view
$data = explode('.', $host);
$n = count($data);
// Judge whether it is a double suffix
$preg = '/[\w].+\.(com|net|org|gov|edu)\.cn$/';
if(($n > 2) && preg_match($preg,$host)){
// Double suffix followed 3 Bit
$host = $data[$n-3].'.'.$data[$n-2].'.'.$data[$n-1];
}else{
// Non-double suffixes take the last two digits
$host = $data[$n-2].'.'.$data[$n-1];
}
return $host;
}
// Test
echo getTopHost("http://ABC.com/s/j?wd=djl"),'<br>';
echo getTopHost("http://www.abc.com/s/j?wd=djl"),'<br>';
echo getTopHost("http://2.www.abc.com/s/j?wd=djl"),'<br>';
echo getTopHost("https://mp.weixin.qq.com/s?__biz=MzA3ODI3ODUzMw=="),'<br>';
echo getTopHost("http://cfi.net.cn/"),'<br>';
echo getTopHost("http://www.cfi.NEt.cn/"),'<br>';
echo getTopHost("https://www.sina.com.cn/?from=kandian"),'<br>';
Run results:
abc.com
abc.com
abc.com
qq.com
cfi.net.cn
cfi.net.cn
sina.com.cn
For more readers interested in PHP related content, please check the topics on this site: "php socket Usage Summary", "php String Usage Summary", "PHP Mathematical Operation Skills Summary", "php Object-Oriented Programming Introduction Tutorial", "PHP Array (Array) Operation Skills Complete Book", "PHP Data Structure and Algorithm Tutorial", "php Programming Algorithm Summary" and "PHP Network Programming Skills Summary"
I hope this article is helpful to everyone's PHP programming.