使用HTML嵌入代码替换文本中的YouTube网址

时间:2011-11-19 20:57:56

标签: php regex

此功能会嵌入youtube视频(如果在字符串中找到)。

我的问题是什么才是最简单的方法来捕获嵌入的视频(iframe,只有第一个,如果有更多)并忽略其余的字符串。

function youtube($string,$autoplay=0,$width=480,$height=390)
{
preg_match('#(v\/|watch\?v=)([\w\-]+)#', $string, $match);
  return preg_replace(
    '#((http://)?(www.)?youtube\.com/watch\?[=a-z0-9&_;-]+)#i',
    "<div align=\"center\"><iframe title=\"YouTube video player\" width=\"$width\" height=\"$height\" src=\"http://www.youtube.com/embed/$match[2]?autoplay=$autoplay\" frameborder=\"0\" allowfullscreen></iframe></div>",
    $string);
}

1 个答案:

答案 0 :(得分:13)

好的,我想我知道你要完成的是什么。用户输入一个文本块(某些评论或其他内容),您会在该文本中找到一个YouTube网址,并将其替换为实际的视频嵌入代码。

以下是我对其进行修改的方法:

function youtube($string,$autoplay=0,$width=480,$height=390)
{
    preg_match('#(?:http://)?(?:www\.)?(?:youtube\.com/(?:v/|watch\?v=)|youtu\.be/)([\w-]+)(?:\S+)?#', $string, $match);
    $embed = <<<YOUTUBE
        <div align="center">
            <iframe title="YouTube video player" width="$width" height="$height" src="http://www.youtube.com/embed/$match[1]?autoplay=$autoplay" frameborder="0" allowfullscreen></iframe>
        </div>
YOUTUBE;

    return str_replace($match[0], $embed, $string);
}

由于您已经使用第一个preg_match()找到了URL,因此无需再运行其他正则表达式函数来替换它。让它与整个网址匹配,然后对整场比赛进行简单的str_replace()$match[0])。视频代码在第一个子模式($match[1])中捕获。我正在使用preg_match(),因为您只想匹配找到的第一个网址。如果您想匹配所有网址,而不仅仅是第一个网址,则必须使用preg_match_all()并稍微修改一下代码。

以下是我的正则表达式的解释:

(?:http://)?    # optional protocol, non-capturing
(?:www\.)?      # optional "www.", non-capturing
(?:
                # either "youtube.com/v/XXX" or "youtube.com/watch?v=XXX"
  youtube\.com/(?:v/|watch\?v=)
  |
  youtu\.be/     # or a "youtu.be" shortener URL
)
([\w-]+)        # the video code
(?:\S+)?        # optional non-whitespace characters (other URL params)