3

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

4 回答 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);
于 2012-05-03T16:42:56.343 回答
0

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

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

编辑尝试,如果不工作;

do{
    $text = preg_replace($search, $replace, $text, -1, $Count);
}
while($Count);
于 2012-05-03T16:38:24.660 回答
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;
?>

测试一下

于 2012-05-03T16:56:40.183 回答
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 中使用输出了!

于 2019-10-02T19:28:26.183 回答