正则表达式匹配 Youtube URL [英] Regex to match Youtube URL's
问题描述
我正在尝试使用正则表达式验证 Youtube URL:
I am trying to validate a Youtube URL using regex:
preg_match('~http://youtube.com/watch\?v=[a-zA-Z0-9-]+~', $videoLink)
它有点工作,但它可以匹配格式错误的 URL.例如,这将匹配 ok:
It kind of works, but it can match URL's that are malformed. For example, this will match ok:
http://www.youtube.com/watch?v=Zu4WXiPRek
但这也会:
http://www.youtube.com/watch?v=Zu4WX£&P!ek
这不会:
http://www.youtube.com/watch?v=!Zu4WX£&P4ek
我认为这是因为 +
运算符.它匹配 v=
之后的第一个字符,当它需要尝试将 v=
后面的所有内容与 [a-zA-Z0-9 进行匹配时-]
.感谢任何帮助,谢谢.
I think it's because of the +
operator. It's matching what seems to be the first character after v=
, when it needs to try and match everything behind v=
with [a-zA-Z0-9-]
. Any help is appreciated, thanks.
推荐答案
问题是您不需要在 URL 的 v= 部分包含任何特定数量的字符.因此,例如,检查
The problem is that you are not requiring any particular number of characters in the v= part of the URL. So, for instance, checking
http://www.youtube.com/watch?v=Zu4WX£&P!ek
会匹配
http://www.youtube.com/watch?v=Zu4WX
因此返回 true.您需要在 v= 部分指定所需的字符数:
and therefore return true. You need to either specify the number of characters you need in the v= part:
preg_match('~http://youtube.com/watch\?v=[a-zA-Z0-9-]{10}~', $videoLink)
或指定组 [a-zA-Z0-9-] 必须是字符串的最后一部分:
or specify that the group [a-zA-Z0-9-] must be the last part of the string:
preg_match('~http://youtube.com/watch\?v=[a-zA-Z0-9-]+$~', $videoLink)
你的另一个例子
http://www.youtube.com/watch?v=!Zu4WX£&P4ek
不匹配,因为+号要求至少一个字符必须匹配[a-zA-Z0-9-].
does not match, because the + sign requires that at least one character must match [a-zA-Z0-9-].
这篇关于正则表达式匹配 Youtube URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!