交换所有YouTube网址以通过preg_replace()嵌入

问题描述 投票:3回答:4

您好,我正在尝试将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;
?>

它适用于一个链接。但是,如果我加两个,它将只交换最后一次出现的时间。我必须更改什么?

php preg-replace
4个回答
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);

0
投票

尝试一下:preg_replace($search, $replace, $text, -1);

我知道这是默认设置,但谁知道...

编辑如果不起作用,请尝试;

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

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;
?>

测试


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中使用输出了!

© www.soinside.com 2019 - 2024. All rights reserved.