tags:

views:

64

answers:

4

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?

+2  A: 

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

TiuTalk
yes I needed the second regex
Dan
A: 

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

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

K Prime
+1  A: 

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
}
robbo
TiuTalk
I really hope you are joking.
robbo
No i'm not: http://dreamfall.blogspot.com/2008/02/php-benchmarks-strpos-vs-pregmatchall.html
TiuTalk
@TiuTalk - (Forgetting the dubious benchmark speed results for now.) What do you mean by "more stable"? And do you think a regex is easier to read and maintain, especially for someone who has to go to SO or some forum every time he needs to change his code?
GZipp
A: 

Like this:

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