URL verification php
The task is to find if t开发者_JAVA技巧he string starts with http:// or https:// or ftp://
$regex = "((https?|ftp)://)?";
but preg_match($regex) does not work correctly. What should I change?
You need to use a delimiter (/) around the RegExp :)
// Protocol's optional
$regex = "/^((https?|ftp)\:\/\/)?/";
// protocol's required
$regex = "/^(https?|ftp)\:\/\//";
if (preg_match($regex, 'http://www.google.com')) {
// ...
}
http://br.php.net/manual/en/function.preg-match.php
Is it necessary to use regex? One could achieve the same thing using string functions:
if (strpos($url, 'http://') === 0 ||
strpos($url, 'https://') === 0 ||
strpos($url, 'ftp://') === 0)
{
// do magic
}
You need: preg_match ('#((https?|ftp)://)?#', $url)
The #
delimiters remove the need to escape /
, which is more convenient for URLs
Like this:
$search_for = array('http', 'https', 'ftp');
$scheme = parse_url($url, PHP_URL_SCHEME);
if (in_array($scheme, $search_for)) {
// etc.
}
精彩评论