The usage for parse_url()
is below, but @wrikken brings up a much better way to simply validate if a URL is 'valid' or not with filter_var()
. parse_url()
simply parses a specified URL string into its component parts, and will apparently not return a false
value unless the URL is catastrophically broken.
filter_var()
is sensitive enough that it will detect something minor like an underscore used in a domain name.
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()
would be better left to extracting portions of a URL that you already know is valid:
var_dump(parse_url('http://stackoverflow.com/questions/19437105/using-regx-how-to-validate-url?noredirect=1#comment28819663_19437105'));
Output:
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"
}
Or how about: