通过preg_replace()交换所有youtube网址以进行嵌入

时间:2012-05-03 16:37:04

标签: php preg-replace

您好我试图将youtube链接转换为嵌入代码。

这就是我所拥有的:

<?php

$text = $post->text;

     $search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*$#x';
     $replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
     $text = preg_replace($search, $replace, $text);


echo $text;
?>

适用于一个链接。但是,如果我添加两个,它将只交换最后一次出现。我需要改变什么?

4 个答案:

答案 0 :(得分:6)

您没有正确处理字符串的结尾。移除$,并将其替换为结束标记</a>。这将解决它。

 $search = '#<a(.*?)(?:href="https?://)?(?:www\.)?(?:youtu\.be/|youtube\.com(?:/embed/|/v/|/watch?.*?v=))([\w\-]{10,12}).*<\/a>#x';
 $replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$2" frameborder="0" allowfullscreen></iframe></center>';
 $text = preg_replace($search, $replace, $text);

答案 1 :(得分:0)

试试这个:preg_replace($search, $replace, $text, -1);

我知道这是默认的,但谁知道......

编辑如果不能正常工作,请尝试;

do{
    $text = preg_replace($search, $replace, $text, -1, $Count);
}
while($Count);

答案 2 :(得分:0)

这是一个更高效的正则表达式:http://pregcopy.com/exp/26,将其转换为PHP :(添加“s”修饰符)

<?php

$text = $post->text;

     $search = '#<a (?:.*?)href=["\\\']http[s]?:\/\/(?:[^\.]+\.)*youtube\.com\/(?:v\/|watch\?(?:.*?\&)?v=|embed\/)([\w\-\_]+)["\\\']#ixs';
     $replace = '<center><iframe width="560" height="315" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe></center>';

     $text = preg_replace($search, $replace, $text);


echo $text;
?>

测试

答案 3 :(得分:0)

一个视频有两种类型的youtube链接:

示例:

$link1 = 'https://www.youtube.com/watch?v=NVcpJZJ60Ao';
$link2 = 'https://www.youtu.be/NVcpJZJ60Ao';

此功能可同时处理以下两者:

function getYoutubeEmbedUrl($url)
{
     $shortUrlRegex = '/youtu.be\/([a-zA-Z0-9_-]+)\??/i';
$longUrlRegex = '/youtube.com\/((?:embed)|(?:watch))((?:\?v\=)|(?:\/))([a-zA-Z0-9_-]+)/i';

    if (preg_match($longUrlRegex, $url, $matches)) {
        $youtube_id = $matches[count($matches) - 1];
    }

    if (preg_match($shortUrlRegex, $url, $matches)) {
        $youtube_id = $matches[count($matches) - 1];
    }
    return 'https://www.youtube.com/embed/' . $youtube_id ;
}

$ link1或$ link2的输出将相同:

 $output1 = getYoutubeEmbedUrl($link1);
 $output2 = getYoutubeEmbedUrl($link2);
 // output for both:  https://www.youtube.com/embed/NVcpJZJ60Ao

现在您可以在iframe中使用输出了!