2012-05-14 63 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");