通常不建议使用基于正则表达式的方法来操作url字符串。业务的第一步是准备parse_url()
的字符串,那么你将有一个坚实的基础从头开始。我使用explode()
和数组函数来提取所需的结果。
代码:(Demo)
$array=['google.com', // -> google.com
'www.google.com', // -> google.com
'www.maps.google.com', // -> maps.google.com
'www.dev.maps.google.com', // - > maps.google.com
'www.dev.maps.google.com/show/maps', // - > maps.google.com
'www.dev.maps.google.com?key=value', // - > maps.google.com
];
foreach($array as $url){
$host=parse_url("http://$url")['host']; // reliable way to isolate host component only
$bits=explode('.',$host); // split string on dots
if($bits[0]==='www'){ // check for www in first element
unset($bits[0]); // remove first element
}
echo implode('.',array_slice($bits,-3)),"\n"; // extract maximum of 3 elements from end, rejoin with dots
}
输出:
google.com
google.com
maps.google.com
maps.google.com
maps.google.com
maps.google.com
此代码不写入验证输入字符串作为一个有效的URL。它假定你将有效的域名提供给它。如果你知道,那么在www.
之后移动的唯一子字符串将是dev.
,那么可以更直接地写出一种方法。
你有任何示例代码? –
技术上'www'仍然是'google.com'的子域名。因此,“www.google.com”将评估为“www.google.com”。 –
切断www可能更为明智。 preg替换前 –