的用法parse_url()
如下,但@wrikken 提出了一种更好的方法来简单地验证 URL 是否“有效” filter_var()
。parse_url()
只是将指定的 URL 字符串解析为其组成部分,并且显然不会返回false
值,除非 URL 被灾难性地破坏。
filter_var()
足够敏感,它会检测到像域名中使用的下划线这样的次要内容。
var_dump(
filter_var(
'http://stack-overflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105',
FILTER_VALIDATE_URL
)
);
//output: string(113) "http://stack-overflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105"
var_dump(
filter_var(
'http://stack_overflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105',
FILTER_VALIDATE_URL
)
);
//output: bool(false)
parse_url()
最好保留提取您已经知道有效的 URL 部分:
var_dump(parse_url('http://stackoverflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105'));
输出:
array(5) {
["scheme"]=>
string(4) "http"
["host"]=>
string(17) "stackoverflow.com"
["path"]=>
string(50) "/questions/19437105/using-regx-how-to-validate-url"
["query"]=>
string(12) "noredirect=1"
["fragment"]=>
string(24) "comment28819663_19437105"
}
或者怎么样: