如何在文本中替换youtube网址?

时间:2012-08-01 21:18:05

标签: php

我有以下文字

"I made this video on my birthday. All of my friends are here in party. Click play to video the video
 http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit "

我想要的是将上面的网址替换为

"I made this video on my birthday. All of my friends are here in party. Click play to video the video

      <iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe> "

我知道我们可以通过以下脚本从上面的网址获取YouTube视频ID

     preg_match("#(?<=v=)[a-zA-Z0-9-]+(?=&)|(?<=v\/)[^&\n]+(?=\?)|(?<=v=)[^&\n]+|(?<=youtu.be/)[^&\n]+#", $word, $matches);


        $youtube_id = $matches[0];

但我不知道如何更换网址

http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit

  <iframe width="853" height="480" src="http://www.youtube.com/embed/G3j6avmJU48" frameborder="0" allowfullscreen></iframe>

请帮助谢谢

2 个答案:

答案 0 :(得分:1)

使用preg_replace函数(see PHP preg_replace() Documentation

修改:

使用preg_replace如下:使用括号()来包装要在正则表达式中捕获的内容(第一个参数),然后在第二个参数中使用$ n(在正则表达式中使用括号顺序)你捕获了什么。

在你的情况下你应该有这样的东西:

$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit";

$replaced = preg_replace('#http://www\.youtube\.com/watch\?v=(\w+)[^\s]+#i','<iframe width="853" height="480" src="http://www.youtube.com/embed/$1" frameborder="0" allowfullscreen></iframe>',$text);

有关更多高级用法和示例,请参阅我之前提供给您的文档链接。

希望这对你有所帮助。

编辑2: 正则表达式是错误的,我修复了它。

答案 1 :(得分:0)

您可以使用此示例代码来实现它,基于@Matt评论:

<?php
$text = "I made this video on my birthday. All of my friends are here in party. Click play to video the video
 http://www.youtube.com/watch?v=G3j6avmJU48&feature=g-all-xit ";

$rexProtocol = '(https?://)?';
$rexDomain   = '(www\.youtube\.com)';
$rexPort     = '(:[0-9]{1,5})?';
$rexPath     = '(/[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]*?)?';
$rexQuery    = '(\?[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';
$rexFragment = '(#[!$-/0-9:;=@_\':;!a-zA-Z\x7f-\xff]+?)?';

function callback($match)
{
    $completeUrl = $match[1] ? $match[0] : "http://{$match[0]}";
    $videoId = array ();
    preg_match ("|\?v=([a-zA-Z0-9]*)|", $match[5], $videoId);

    return '<iframe src="http://www.youtube.com/embed/' . $videoId[1] . '" width="853" height="480"></iframe>';
}
print preg_replace_callback("&\\b$rexProtocol$rexDomain$rexPort$rexPath$rexQuery$rexFragment(?=[?.!,;:\"]?(\s|$))&", 'callback', htmlspecialchars($text));

?>