我有这个文本输入,我需要检查字符串是否是有效的网址,如http://www.example.com
。如何在PHP中使用正则表达式?
答案 0 :(得分:1)
答案 1 :(得分:0)
发现这个:
(http|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?
从这里开始:
A regex that validates a web address and matches an empty string?
答案 2 :(得分:0)
在开始有效解析之前,您需要首先了解网址。是的,http://www.example.com是有效的地址。 www.example.com也是如此。或者example.com。或http://example.com。或者是prefix.example.com。
查看URI的规范,尤其是Syntax components。
答案 3 :(得分:0)
我在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);
答案 4 :(得分:0)
在大多数情况下,您不必检查字符串是否为有效地址。
它是,并且一个网站将可用或不会,用户将返回。
你应该只是逃避非法人物以避免XSS,如果你的用户不想要提供有效的网站,那应该是他的问题。
(在大多数情况下)。
PS:如果您仍想查看网址,请查看nikic的回答。
答案 5 :(得分:0)
要匹配更多协议,您可以执行以下操作:
((https?|s?ftp|gopher|telnet|file|notes|ms-help)://)?[\w:#@%/;$()~=\.&-]+