2009-07-02 56 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); 

會告訴你它是指域名。

它可能比一些瘋狂的正則表達式更清晰,更易維護。