我正在爲我的網站編寫一些代碼,我需要找出一種方法來檢測用戶的輸入並確定它是否是域或IP。如果它是一個域,它將從例如http://www.google.com
至google.com
,然後將其解析並將其回顯回到用戶輸入字段。如果它是IP,那麼它將跳過所有這些步驟並保留在IP用戶輸入字段中。如何檢測用戶輸入是否爲域名?
這是我到目前爲止有:
<?php
if($_POST['submit'])
{
$ip_address=$_POST["host"];
if (ctype_alpha($ip_address))
{
// get host name from URL
preg_match('@^(?:http://)?([^/]+)@i', $ip_address, $matches);
$host = $matches[1];
// get last two segments of host name
preg_match('/[^.]+\.[^.]+$/', $host, $matches);
$new_ip_address = $matches;
//resolve parsed ip
$presolved = gethostbyname($new_ip_address);
}
else
{
echo "Do stuff.\n";
}
}
?>
我不認爲「http://」(或缺少)會影響IP地址,除非這純粹是爲了在網頁上顯示 - 瀏覽器將假定該協議。另外,「https」呢? –
@邁克爾喜歡它! user2934716你應該看看在這個問題上接受的答案:http://stackoverflow.com/a/11046121/2812842 –
我會使用一個類似於'(?:^。*?//)的正則表達式?(。* ?)[:/]?'來捕獲「可能的域名」。這應該與'http://foo.com:80','// foo.com','foo.com/bar'等'foo.com'匹配。如果'foo.com'沒有發生解決IP或他們「意外地離開子域」然後..哦,好吧:你試圖幫助。 – user2864740