如何替换文本中的youtubeurl


how to replace youtube url in 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 "

我想要的是将上面的url替换为

"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> "

我知道我们可以在下面的脚本中从上面的url获得youtube视频id

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

        $youtube_id = $matches[0];

但是我不知道如何替换url

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>

请帮忙谢谢

使用preg_replace函数(请参阅PHP preg_replay()文档)

编辑:

使用preg_replace如下:使用括号()将要捕获的内容包装在regex中(第一个参数),然后在第二个参数中使用$n(n是regex中括号的顺序)来获取捕获的内容。

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

$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:正则表达式错误,我修复了它。

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

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