How to check if a given value is a valid URL
I need some function to check is the given value is a url.
I have code:
<?ph开发者_开发知识库p
$string = get_from_db();
list($name, $url) = explode(": ", $string);
if (is_url($url)) {
$link = array('name' => $name, 'link' => $url);
} else {
$text = $string;
}
// Make some things
?>
If you're running PHP 5 (and you should be!), just use filter_var()
:
function is_url($url)
{
return filter_var($url, FILTER_VALIDATE_URL) !== false;
}
Addendum: as the PHP manual entry for parse_url()
(and @Liutas in his comment) points out:
This function is not meant to validate the given URL, it only breaks it up into the above listed parts. Partial URLs are also accepted, parse_url() tries its best to parse them correctly.
For example, parse_url()
considers a query string as part of a URL. However, a query string is not entirely a URL. The following line of code:
var_dump(parse_url('foo=bar&baz=what'));
Outputs this:
array(1) {
["path"]=>
string(16) "foo=bar&baz=what"
}
use parse_url
and check for false
<?php
$url = 'http://username:password@hostname/path?arg=value#anchor';
print_r(parse_url($url));
echo parse_url($url, PHP_URL_PATH);
?>
The above example will output:
Array
(
[scheme] => http
[host] => hostname
[user] => username
[pass] => password
[path] => /path
[query] => arg=value
[fragment] => anchor
)
/path
You can check if ParseUrl returns false.
精彩评论