【发布时间】:2010-08-30 15:22:05
【问题描述】:
我有这个文本输入,我需要检查字符串是否是有效的网址,例如http://www.example.com。 PHP中的正则表达式怎么做?
【问题讨论】:
-
语法有效和/或语义有效?
-
nikic 的答案是完美的,这是:hashbangcode.com/blog/…。谢谢大家。
标签: php regex validation
我有这个文本输入,我需要检查字符串是否是有效的网址,例如http://www.example.com。 PHP中的正则表达式怎么做?
【问题讨论】:
标签: php regex validation
【讨论】:
找到这个:
(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
从这里:
A regex that validates a web address and matches an empty string?
【讨论】:
www.mywebsite.com 在任何地方都不是有效的网站,除非您在地址栏中输入它(假设为http://)。在大多数其他情况下,它被假定为一个文件名(因此将是一个相对路径)。因此,如果您希望它验证或不验证,这取决于您的确切用途(个人而言,如果不存在,我会在前面加上 http://,然后通过这样的检查,或 filter_var)...
您需要先了解一个网址,然后才能开始有效地解析它。是的,http://www.example.com 是一个有效地址。 www.example.com 也是如此。或 example.com。或http://example.com。或前缀.example.com。
查看 URI 的规范,尤其是 Syntax components。
【讨论】:
我从http://www.roscripts.com/PHP_regular_expressions_examples-136.html找到以下内容
//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into backreferenes 1 through 4
'\b((?#protocol)https?|ftp)://((?#domain)[-A-Z0-9.]+)((?#file)/[-A-Z0-9+&@#/%=~_|!:,.;]*)?((?#parameters)\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?'
//URL: Different URL parts
//Protocol, domain name, page and CGI parameters are captured into named capturing groups.
//Works as it is with .NET, and after conversion by RegexBuddy on the Use page with Python, PHP/preg and PCRE.
'\b(?<protocol>https?|ftp)://(?<domain>[-A-Z0-9.]+)(?<file>/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(?<parameters>\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?'
//URL: Find in full text
//The final character class makes sure that if an URL is part of some text, punctuation such as a
//comma or full stop after the URL is not interpreted as part of the URL.
'\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]'
//URL: Replace URLs with HTML links
preg_replace('\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[-A-Z0-9+&@#/%=~_|]', '<a href="\0">\0</a>', $text);
【讨论】:
www.mywebsite.com 不是绝对 URL;它只会被解释为 URL 路径。
在大多数情况下,您不必检查字符串是否为有效地址。
要么是,网站将可用,要么不可用,用户将直接返回。
你应该只转义非法字符以避免 XSS,如果你的用户不想给一个有效的网站,那应该是他的问题。
(在大多数情况下)。
PS:如果你还想查看网址,请查看 nikic 的回答。
【讨论】:
要匹配更多协议,您可以这样做:
((https?|s?ftp|gopher|telnet|file|notes|ms-help)://)?[\w:#@%/;$()~=\.&-]+
【讨论】: