【问题标题】:PHP BBCode to parse youtube urlsPHP BBCode 解析 youtube 网址
【发布时间】:2012-09-03 11:50:46
【问题描述】:

我已经研究这个问题将近 5 小时了,我能想到的最好的就是 Stackoverflow 帖子中的这段代码:

<?php
$pattren = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/]{11})%i';
?>

我想要完成的是我有一个由其他人编写的定制网络论坛,我想添加直接在论坛主题中观看 YouTube 视频的功能,我尝试了不同的代码和模式,最好的一个是我的已经发布在这篇文章中,它几乎可以匹配任何 YouTube 链接,但是我无法用这段代码解决一个问题,论坛中使用的 BBCode 标签是[yt]youtubelink[/yt],我尝试在模式前加上

<?php
$pattren = '%\[yt\](?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/]{11})[\/yt]%i';
?>

但它不起作用,没有任何错误报告表明模式存在问题

我使用的完整代码

<?php

$testmessage = "test youtube links [yt]http://www.youtube.com/watch?v=ZCLAwp2HbW4&feature=player_embedded[/yt] more text";
$pattren1    = '%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})%i';
$pattren2    = '%\[yt\](?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})[\/yt]%i';

echo '<h1>works:-</h1>';
echo preg_replace($pattren1, '<iframe width="350" height="250" sandbox="" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>', $testmessage);
echo '<h1>doesnt work:-</h1>';
echo preg_replace($pattren2, '<iframe width="350" height="250" sandbox="" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>', $testmessage);
?> 

虽然第一个模式部分有效,但它也会留下一些 URL 查询字符串,例如第一个模式在它确实有效并获取视频 ID 时,它将这部分留在文本消息中 &amp;feature=player_embedded

更新:

我无法让它直接使用 preg_replace,所以我想出了不同的方法来解决这个问题,我会发布代码,它可能对某人有用,这样他就不会浪费 6 小时他的生活再次在这个问题上!

<?php
$test = "test youtube links [yt]http://www.youtube.com/watch?v=ZCLAwp2HbW4&feature=player_embedded[/yt] more text";
echo preg_replace_callback('#\[yt\](.*)\[/yt\]#i', function ($matches) {
    $regex = '#(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&]v=)|youtu\.be/)([^"&?/ ]{11})#i';
        preg_match($regex, $matches[1], $found);
        if ($found[1])
            return '<iframe width="350" height="250" sandbox="" src="http://www.youtube.com/embed/'.$found[1].'" frameborder="0" allowfullscreen></iframe>';

}, $test);
?>

此代码适用于 PHP 5.3 以使其适用于

【问题讨论】:

  • 只使用正则表达式很难正确解析 bbcode,因为 bbcodes 标签可以是递归的。
  • 我设法使用正则表达式实现了最常用的代码,我发现的唯一问题是 YouTube 链接器!
  • 哦,如果您有答案,请发布!我个人尝试了一种与使用正则表达式(在 ruby​​ 中)不同的方法,它对我来说效果很好(虽然我还没有对其进行广泛的测试)。
  • 我发布了 youtube bbcode,还是您想要其他 bbcode 标签?

标签: php regex bbcode


【解决方案1】:

如果这真的是解决方案,你会打自己的耳光!你错过了最后方括号的转义:[/yt] 应该是\[/yt\]

【讨论】:

  • 当前代码确实可以正常工作而不会转义最后一个方块,但我会更新答案以保持一致,感谢您的提示!
猜你喜欢
  • 2011-04-05
  • 1970-01-01
  • 2011-03-14
  • 2015-02-24
  • 1970-01-01
  • 2010-11-17
  • 2022-01-03
  • 2011-10-10
相关资源
最近更新 更多