php PHP正则表达式匹配所有网址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16481641/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
PHP regex match all urls
提问by André Figueira
I need help creating a Regex that will match all urls for example, please do not close question as a duplicate as I have been looking for what i need for a long time, and none of the answers i have seen have given an answer that solves my problem.
我需要帮助创建一个匹配所有 url 的正则表达式,例如,请不要将问题作为重复关闭,因为我一直在寻找我需要的东西很长一段时间,我看到的答案都没有给出解决的答案我的问题。
website.com
网站.com
www.website.com
www.website.com
with also anything trailing
也有任何拖尾
www.website.com/path-to-something
www.website.com/path-to-something
I am coding something that shortens any url, but to do so, first i need to match them all.
我正在编写一些可以缩短任何 url 的代码,但要这样做,首先我需要将它们全部匹配。
Thanks
谢谢
回答by Lakatos Gyula
This one match correctly all you posted:
这一项正确匹配您发布的所有内容:
preg_match_all('#[-a-zA-Z0-9@:%_\+.~\#?&//=]{2,256}\.[a-z]{2,4}\b(\/[-a-zA-Z0-9@:%_\+.~\#?&//=]*)?#si', $targetString, $result);
回答by cryptic ツ
You want to use something like this:
你想使用这样的东西:
$string = 'www.blah.com';
$temp_string = (!preg_match('#^(ht|f)tps?://#', $string)) // check if protocol not present
? 'http://' . $string // temporarily add one
: $string; // use current
if (filter_var($temp_string, FILTER_VALIDATE_URL))
{
echo 'is valid';
} else {
echo 'not valid';
}
This uses PHP's build in URL validation. It will first check to see if a protocol is present, if it is not it will temporarily add one to a string to be checked then run it through validation. This is accurate unlike the currently accepted answer.
这使用 PHP 的内置 URL 验证。它将首先检查协议是否存在,如果不存在,它将临时向要检查的字符串添加一个,然后通过验证运行它。与当前接受的答案不同,这是准确的。
回答by Vishal Purohit
You can use the following trick :
您可以使用以下技巧:
$url = "your URL"
$validation = "/^(http|https|ftp):\/\/([A-Z0-9][A-Z0-9_-]*(?:\.[A-Z0-9][A-Z0-9_-]*)+):?(\d+)?\/?/i";
if((bool)preg_match($validation, $url) === false)
echo 'Not a valid URL';
I think it may works for you.
我认为它可能对你有用。
回答by Danack
Don't use a regex. There's a PHP function for doing what you want.
不要使用正则表达式。有一个 PHP 函数可以做你想做的事。