【问题标题】:Fixing a preg_match rule not to match the start of a tag "<"修复 preg_match 规则不匹配标签“<”的开头
【发布时间】:2013-01-11 18:18:36
【问题描述】:

我有这个 preg_match 规则,可以将普通的 youtube 链接转换为实际的播放器 html 代码:

preg_match('#(?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?)|youtu\.be/)([\w-]+)(?:\S+)?#', $text, $youtube_match);

1) 如果我在视频链接后面有一个标签,比如说 br 标签:http://www.youtube.com/watch?v=4rUGhlNCNho&lt;br /&gt;,它就不起作用了,它可能认为&lt;br 是 URL 的一部分。

2) 我应该如何修改规则以匹配 url 变量的混合顺序,例如:

http://www.youtube.com/watch?feature=player_embedded&amp;v=4rUGhlNCNho 代替 http://www.youtube.com/watch?v=4rUGhlNCNho

【问题讨论】:

  • 我该怎么做?代码是别人写的,我不擅长正则表达式。

标签: regex youtube preg-match expression


【解决方案1】:

如果我是正确的,你只需要参数 v= 来生成和嵌入视频

preg_match('#(?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?)|youtu\.be/)[a-z0-9A-Z\-_\=\&\%\?]*v\=([a-zA-Z0-9]+)#', $text, $youtube_match);

【讨论】:

  • 谢谢,这就是诀窍,我在最后添加了一个额外的([a-zA-Z0-9=&amp;_]+)?,以便它在 v=foo 之后也匹配(但不获取)其他变量:preg_match('#(?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?)|youtu\.be/)[a-z0-9A-Z\-_\=\&amp;\%\?]*v\=([a-zA-Z0-9]+)([a-zA-Z0-9=&amp;_]+)?#', $text, $youtube_match);
【解决方案2】:

GreenRover 回答后我的最终代码:

preg_match('#(?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?)|youtu\.be/)[a-z0-9A-Z\-_\=\&\%\?]*v\=([a-zA-Z0-9]+)([a-zA-Z0-9=&_]+)?#', $text, $youtube_match);

这匹配了这些不同的情况(以带有附加文本的新行结尾,以 BR 标记结尾等):

"http://www.youtube.com/watch?v=4rUGhlNCNho&feature=player_embedded" "http://www.youtube.com/watch?feature=player_embedded&v=4rUGhlNCNho " "http://www.youtube.com/watch?v=4rUGhlNCNho&feature=player_embedded\nETC" "http://www.youtube.com/watch?v=4rUGhlNCNho&feature=player_embedded " "http://www.youtube.com/watch?v=4rUGhlNCNho&feature=player_embedded<br />"

【讨论】:

    【解决方案3】:

    由于PCRE dosent 支持在lookbehind 中进行可变复制,所以您可以使用它

    (?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?)|youtu\.be/)([\w-]+)(?:\S+)?$(?<!>)
    

    其他正则表达式风格,你可以使用这个

    (?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?)|youtu\.be/)([\w-]+)(?:\S+)?$(?<!<[^>]*>)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-02-29
      • 2014-10-19
      • 2011-01-11
      • 2011-03-14
      • 1970-01-01
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      相关资源
      最近更新 更多