用HTML嵌入代码替换文本中的YouTube URL


Replace YouTube URL in text with its HTML embed code

如果在字符串中找到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);
}

好了,我想我明白你想要达到的目的了。用户输入一个文本块(一些评论或其他),你在该文本中找到一个YouTube URL,并将其替换为实际的视频嵌入代码。

我是这样修改它的:

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,因此不需要运行另一个regex函数来替换它。让它匹配整个URL,然后对整个匹配($match[0])进行简单的str_replace()。视频代码在第一个子模式($match[1])中捕获。我使用preg_match(),因为你只想匹配找到的第一个URL。如果你想匹配所有的url,你必须使用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)