3

我有以下文字

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

我知道我们可以在以下脚本中从上面的 url 获取 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>

请帮忙谢谢

4

2 回答 2

1

使用 preg_replace 函数(参见 PHP preg_replace() 文档

编辑 :

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

于 2012-08-01T21:22:53.697 回答
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));

?>
于 2012-08-01T21:43:23.060 回答