Dan
Dan

Reputation: 57971

URL verification php

The task is to find if the string starts with http:// or https:// or ftp://

$regex = "((https?|ftp)://)?";

but preg_match($regex) does not work correctly. What should I change?

Upvotes: 0

Views: 505

Answers (4)

GZipp
GZipp

Reputation: 5426

Like this:

$search_for = array('http', 'https', 'ftp');
$scheme = parse_url($url, PHP_URL_SCHEME);
if (in_array($scheme, $search_for)) {
    // etc.
}

Upvotes: 0

robbo
robbo

Reputation: 234

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
}

Upvotes: 1

Thiago Belem
Thiago Belem

Reputation: 7832

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

Upvotes: 3

K Prime
K Prime

Reputation: 5849

You need: preg_match ('#((https?|ftp)://)?#', $url)

The # delimiters remove the need to escape /, which is more convenient for URLs

Upvotes: 0

Related Questions