views:

31

answers:

4

I am trying to match a Youtube URL with regex to see if it is valid. This is my code:

if(preg_match('\bhttp://youtube.com/watch\?v=.*\b', $link))
{
    echo "matched youtube";
}

But I'm getting an error:

Warning:  preg_match() [function.preg-match]: Delimiter must not be alphanumeric or backslash in C:\xampp\htdocs\ajax\youtube.php on line 22

I'll admit I am a complete novice to regular expressions and I don't understand them much but I am trying to learn as I do this. I made the above regex using this online regex tool:

http://gskinner.com/RegExr/

and it works there. So what am I doing wrong and is there a better way to validate a youtube URL?

Thanks. :)

+1  A: 

There's really no need for preg_match here:

$url = "http://youtube.com/watch?v=abc";
if(strpos($url, "http://youtube.com/watch?v=") === 0) {
    echo "Valid";
}
halfdan
A: 

You should add addition delimeters to your regexp. This is used to supply optional parameters:

preg_match('"\bhttp://youtube.com/watch\?v=.*\b"', $link) 

Symbol / is usually used as regexp delimeter, but in your case it'll force inner / to be escaped. So for more clear view I suggest to use ".

Ivan Nevostruev
+1  A: 

PCRE require delimiters that separate the regular expressions and optional modifiers.

In this case the \ is assumed but \ is not a valid delimiter (see error message). Use a different character like ~:

preg_match('~\bhttp://youtube\.com/watch\?v=.*\b~', $link)
Gumbo
A: 

When using preg_match, then the regexp needs to be enclosed with proper delimiters.

For example:

preg_match('/\bhttp://youtube.com/watch\?v=.*\b/', $link)

In your example \b stands for word boundary, this is not a valid alphanumeric delimiter, hence the error message

Anti Veeranna