2009-07-02 58 views
2

我一直在尝试自己和在线搜索来编写此正则表达式,但没有成功。使用正则表达式的特定网域网址验证

我需要验证给定的URL是来自特定的域和格式良好的链接(在PHP中)。例如:

好域名:example.com

来自example.com的那么好网址:

所以不良网址不是:

一些注意事项: 我不在乎 “HTTP” VERUS “https”,但如果它重要,你认为“http”总是 将使用此正则表达式的代码是PHP所以加分那。

UPDATE 2010:

格鲁伯增加了一个伟大的URL正则表达式:

?i)\b((?:[a-z][\w-]+:(?:/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}/)(?:[^\s()<>]+|\(([^\s()<>]+|(\([^\s()<>]+\)))*\))+(?:\(([^\s()<>]+|(\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:'".,<>?«»“”‘’])) 

见他的职位:An Improved Liberal, Accurate Regex Pattern for Matching URLs

+0

您的“良好域”示例是**不是**有效的URL(缺少路径)。 – 2009-07-02 14:04:09

+0

@Nikolar Ruhe:路径实际上是可选的:“http://”hostport [“/”hpath [“?”搜索]](请参阅RFC 1738) – Gumbo 2009-07-02 14:07:32

+0

这不是指示有效的URL,而是它指示示例URL使用的有效域,但也许我应该只说'blah.com',不再提供。无论哪种方式,我认为这一点是成立的。 – donohoe 2009-07-02 14:08:16

回答

5

我刺它

<?php 

$pattern = "#^https?://([a-z0-9-]+\.)*blah\.com(/.*)?$#"; 

$tests = array(
    'http://blah.com/so/this/is/good' 
    , 'http://blah.com/so/this/is/good/index.html' 
    , 'http://www.blah.com/so/this/is/good/mice.html#anchortag' 
    , 'http://anysubdomain.blah.com/so/this/is/good/wow.php' 
    , 'http://anysubdomain.blah.com/so/this/is/good/wow.php?search=doozy' 
    , 'http://any.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case 
    , 'http://999.sub-domain.blah.com/so/this/is/good/wow.php?search=doozy' // I added this case 
    , 'http://obviousexample.com' 
    , 'http://bbc.co.uk/blah.com/whatever/you/get/the/idea' 
    , 'http://blah.com.example' 
    , 'not/even/a/blah.com/url' 
); 

foreach ($tests as $test) 
{ 
    if (preg_match($pattern, $test)) 
    { 
    echo $test, " <strong>matched!</strong><br>"; 
    } else { 
    echo $test, " <strong>did not match.</strong><br>"; 
    } 
} 

// Here's another way 
echo '<hr>'; 
foreach ($tests as $test) 
{ 
    if ($filtered = filter_var($test, FILTER_VALIDATE_URL)) 
    { 
    $host = parse_url($filtered, PHP_URL_HOST); 
    if ($host && preg_match("/blah\.com$/", $host)) 
    { 
     echo $filtered, " <strong>matched!</strong><br>"; 
    } else { 
     echo $filtered, " <strong>did not match.</strong><br>"; 
    } 
    } else { 
    echo $test, " <strong>did not match.</strong><br>"; 
    } 
} 
0
\b(https?)://([-A-Z0-9]+\.)*blah.com(/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(\?[A-Z0-9+&@#/%=~_|!:,.;]*)? 
0
!^https?://(?:[a-zA-Z0-9-]+\.)*blah\.com(?:/[^#]*(?:#[^#]+)?)?$! 
1

也许:

^https?://[^/]*blah\.com(|/.*)$ 

编辑:

防范http://editblah.com

^https?://(([^/]*\.)|)blah\.com(|/.*)$ 
7

你必须使用正则表达式? PHP有很多内置函数用于做这种事情。

filter_var($url, FILTER_VALIDATE_URL) 

会告诉你,如果一个URL是否有效,以及

$domain = parse_url($url, PHP_URL_HOST); 

会告诉你它是指域名。

它可能比一些疯狂的正则表达式更清晰,更易维护。