开发者

preg_match troubles

开发者 https://www.devze.com 2023-01-16 12:08 出处:网络
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))

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 开发者_如何学Cworks there. So what am I doing wrong and is there a better way to validate a youtube URL?

Thanks. :)


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";
}


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)


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 ".


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

0

精彩评论

暂无评论...
验证码 换一张
取 消