PHP BBCode解析youtube网址

时间:2012-09-10 15:16:54

标签: php regex bbcode

我已经研究了这个问题差不多5小时了,我能想到的最好的是来自Stackoverflow的这段代码:

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

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

<?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 &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,使其可以在&lt; PHP5.3将匿名函数移动到单独的函数。

1 个答案:

答案 0 :(得分:1)

如果这实际上是解决方案,那么你就要打自己吧!你最后错过了方括号中的逃脱:[/yt]应为\[/yt\]