【问题标题】:Replace YouTube URL in text with its HTML embed code将文本中的 YouTube URL 替换为其 HTML 嵌入代码
【发布时间】:2012-01-02 02:15:46
【问题描述】:

如果在字符串中找到,此函数会嵌入 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);
}

【问题讨论】:

  • 最简单、最可靠的方法是不使用正则表达式。
  • @FailedDev 想告诉我如何(不必是相同的功能)?
  • 您正在使用 $string 传递部分 html 对吗?你怎么得到那个字符串?
  • 我把你的问题读了五遍,脑海中不断出现一个问题:“输入字符串是什么?”
  • 该功能目前用于用户发帖自动嵌入yt视频。我正在尝试使用相同的功能(或逻辑)让用户使用 youtube 视频作为他们的头像。

标签: php regex


【解决方案1】:

好的,我想我明白你想要完成什么了。用户输入一段文本(一些评论或其他内容),然后您在该文本中找到一个 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,因此无需运行另一个正则表达式函数来替换它。让它匹配整个 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)

【讨论】:

  • 我一直在网上搜索这个脚本。这个有效,但它只检测内容中的第一个 url。例如,我在内容中有 3 个 youtube 网址。第一个视频将嵌入,而其他视频仅显示链接。我该怎么办?
  • 我明白了!只需将preg_match 更改为preg_match_all...谢谢百万!
  • 为了进一步改善这一点,也添加 https 支持 :)
猜你喜欢
  • 2012-08-03
  • 2014-01-21
  • 2011-03-15
  • 2013-03-27
  • 2015-03-02
  • 2011-06-27
  • 2012-01-22
  • 2012-07-22
  • 2014-01-21
相关资源
最近更新 更多