2012-05-14 65 views
0

我想檢查一個URL以查看它是否是Google網址。檢查URL是否爲Google

,如果我嘗試

if (isValidURL('http://google.com/')){ 
    echo 'yes its google url'; 
} 

它正常工作,我有了這個功能

function isValidURL($url) 
{ 
    return preg_match('|^http(s)?://google.com|i', $url); 
} 

。但如果我嘗試

if (isValidURL('http://www.google.com/')){ 
    echo 'yes its google url'; 
} 

(與www)我得到一個錯誤!

+1

你得到一個實際的錯誤?什麼是錯誤? –

+1

我認爲海報只是意味着他的表情與他的正則表達式不匹配。 – Tim

+0

@蒂姆根本沒有,我認爲馬庫斯想要確切的錯誤。有時候這樣做時,瀏覽器會顯示一條消息,如「警告:表達式的分隔符不正確」或blabla關於正則表達式,您知道要解決什麼問題。 –

回答

4

當然,因爲你的正則表達式是不是準備好處理www.

嘗試

function isValidURL($url) 
{ 
    return preg_match('|^http(s)?://(www\.)?google\.com|i', $url); 
} 
+0

是的,我知道它沒有準備好處理www。 ,,,我不是親preg_match,我不知道如何添加www的名單,反正它知道工作很好,比你非常 –

+0

當心'http:// images.google.com /'或'http :// plus.google.com /'。這些也是Google網址,但您不會使用它捕獲它們。如果你不需要它們,那很好。 – ccKep

+0

@Alaa你做了同樣的事情與https –

0

如果你打算支持谷歌的子域,請嘗試:

preg_match('/^https?:\/\/(.+\.)*google\.com(\/.*)?$/is', $url) 
+0

我要提出一個新的問題,知道如何支持子域名!感謝ccKep的補充 –

0

我喜歡使用PHP的parse_url函數來分析url的。它返回一個包含URL的每個部分的數組。這樣你就可以確定你正在檢查正確的部分,並且不會被https或查詢字符串拋出。

function isValidUrl($url, $domain_to_check){ 
     $url = parse_url($url); 
     if (strstr($url['host'], $domain_to_search)) 
      return TRUE; 
     return FALSE; 
    } 

用法:

isValidUrl("http://www.google.com/q=google.com", "google.com");