2013-11-25 28 views
2

我必須承認,我從來沒有習慣使用正則表達式,但是最近我遇到了一個問題,那裏的解決方案比使用正則表達式更麻煩。我需要能夠匹配任何在字符串開始處遵循以下模式的任何內容: {any_url_safe_word} +("/http://" || "/https://" || "www.")+ {any word}。 所以下面應該匹配:在URL中匹配特定的正則表達式的話

  • cars/http://google.com#test
  • cars/https://google.com#test
  • cars/www.google.com#test

的follwing不應該匹配:

  • cars/httdp://google.com#test
  • cars/http:/google.com#test

我試過到目前爲止:^[\w]{1,500}\/[(http\:\/\/)|(https:\/\/])|([www\.])]{0,50},但與從cars/httpd://google.comcars/http

+0

什麼是{any_url_safe_word}? – user4035

+0

例如:cars,ca_rs,ca_1_rs等。不是「c a r s」。 – Babiker

回答

0
<?php 
$words = array(
    'cars/http://google.com#test', 
    'cars/https://google.com#test', 
    'cars/www.google.com#test', 
    'cars/httdp://google.com#test', 
    'cars/http:/google.com#test', 
    'c a r s/http:/google.com#test' 
    ); 

foreach($words as $value) 
{ 
    /* 
     \S+   - at least one non-space symbol 
     \/   - slash 
     (https?:\/\/) - http with possible s then :// 
     |    - or 
     (www\.)  - www. 
     .+   - at least one symbol 
    */ 
    if (preg_match('/^\S+\/(https?:\/\/)|(www\.).+/', $value)) 
    { 
     print $value. " good\n"; 
    } 
    else 
    { 
     print $value. " bad\n"; 
    } 
} 

打印:

cars/http://google.com#test good 
cars/https://google.com#test good 
cars/www.google.com#test good 
cars/httdp://google.com#test bad 
cars/http:/google.com#test bad 
c a r s/http:/google.com#test bad 
3

此正則表達式可以這樣做:

^[\w\d]+\/(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3} 

如果你想要得到它之後談到的一切,你可以再補充(.*)到最後.. 。

Live DEMO

enter image description here

而且由於它似乎的URL安全的話或多或少總清單包含ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-._~:/?#[]@!$&'()*+,;=Source,您可以加入,所以你會(後簡化)獲得:

^[!#$&-.0-;=?-\[\]_a-z~]+\/(?:https?:\/\/)?(?:www\.)?[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3} 
+0

不是那麼簡單:一個很好的正則表達式,僅用於域名模式匹配,來自http://hexillion.com/samples/將是'^(?:[a-zA-Z0-9](?:[a- ZA-Z0-9 \ - ]){0,61} [A-ZA-Z0-9] \)* [A-ZA-Z0-9]((\?!):?。?[A-ZA -Z0-9 \ - ](?!$)){0,61} [a-zA-Z0-9]?$' – CD001

+0

確實,匹配域模式非常複雜,我只是選擇了適合他的最簡單的版本需要(我希望是這樣) – Enissay

+0

嘿 - 是的,放下'\ w \ d ...'爲你允許的'[...]'中的字符列表,你應該是我認爲的好。 – CD001

0

查看demo

[a-z0-9-_.~]+/(https?://|www\.)[a-z0-9]+\.[a-z]{2,6}([/?#a-z0-9-_.~])*

編輯:採取@ CD001意見考慮進去。如果您不介意區分大小寫,請務必使用i修飾符。

+0

使用'\ w'的問題是它匹配任何Perl「word」字符,並且根據PHP正在運行的語言環境而變化 - 從技術上講,您將匹配像'Ö'這樣的字符,它們是**不是**有效的URL字符(尚未)。 – CD001