通常不建議使用基於正則表達式的方法來操作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替換前 –