我一直在嘗試自己和在線搜索來編寫此正則表達式,但沒有成功。使用正則表達式的特定網域網址驗證
我需要驗證給定的URL是來自特定的域和格式良好的鏈接(在PHP中)。例如:
好域名:example.com
來自example.com的那麼好網址:
- http://example.com/so/this/is/good
- http://example.com/so/this/is/good/index.html
- http://www.examle.com/so/this/is/good/mice.html#anchortag
- http://anysubdomain.example.com/so/this/is/good/wow.php
- http://anysubdomain.example.com/so/this/is/good/wow.php?search=doozy 來自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
您的「良好域」示例是**不是**有效的URL(缺少路徑)。 – 2009-07-02 14:04:09
@Nikolar Ruhe:路徑實際上是可選的:「http://」hostport [「/」hpath [「?」搜索]](請參閱RFC 1738) – Gumbo 2009-07-02 14:07:32
這不是指示有效的URL,而是它指示示例URL使用的有效域,但也許我應該只說'blah.com',不再提供。無論哪種方式,我認爲這一點是成立的。 – donohoe 2009-07-02 14:08:16