正则表达式模式,以匹配带有或不带有http://www的url [英] Regular expression pattern to match url with or without http://www
问题描述
我根本不擅长正则表达式.
I'm not very good at regular expressions at all.
到目前为止,我一直在使用许多框架代码,但是我找不到能够与http://www.example.com/etcetc
之类的URL匹配但又能够捕获诸如www.example.com/etcetc
和example.com/etcetc
之类的URL的代码.
I've been using a lot of framework code to date, but I'm unable to find one that is able to match a URL like http://www.example.com/etcetc
but also is able to catch something like www.example.com/etcetc
and example.com/etcetc
.
任何帮助都会很棒.谢谢你们!
Any help would be great. Thanks guys!
推荐答案
要匹配所有类型的URL,应使用以下代码:
For matching all kind of URLs following code should work:
<?php
$regex = "((https?|ftp)://)?"; // SCHEME
$regex .= "([a-z0-9+!*(),;?&=$_.-]+(:[a-z0-9+!*(),;?&=$_.-]+)?@)?"; // User and Pass
$regex .= "([a-z0-9\-\.]*)\.(([a-z]{2,4})|([0-9]{1,3}\.([0-9]{1,3})\.([0-9]{1,3})))"; // Host or IP
$regex .= "(:[0-9]{2,5})?"; // Port
$regex .= "(/([a-z0-9+$_%-]\.?)+)*/?"; // Path
$regex .= "(\?[a-z+&\$_.-][a-z0-9;:@&%=+/$_.-]*)?"; // GET Query
$regex .= "(#[a-z_.-][a-z0-9+$%_.-]*)?"; // Anchor
?>
然后,检查正则表达式的正确方法如下:
Then, the correct way to check against the regex is as follows:
<?php
if(preg_match("~^$regex$~i", 'www.example.com/etcetc', $m))
var_dump($m);
if(preg_match("~^$regex$~i", 'http://www.example.com/etcetc', $m))
var_dump($m);
?>
Courtesy:
splattermania 在PHP手册上发表的评论:
Courtesy:
Comments made by splattermania on PHP manual: http://php.net/manual/en/function.preg-match.php
RegEx Demo in regex101
这篇关于正则表达式模式,以匹配带有或不带有http://www的url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!