Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 将文本中的YouTube URL替换为其HTML嵌入代码_Php_Regex - Fatal编程技术网

Php 将文本中的YouTube URL替换为其HTML嵌入代码

Php 将文本中的YouTube URL替换为其HTML嵌入代码,php,regex,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://)?(ww

如果在字符串中找到,此函数将嵌入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($string,$autoplay=0,$width=480,$height=390)
{
preg#u match('#(v\/| watch\?v=)([\w\-]+)#',$string,$match);
返回预更换(
“#”(http://www.youtube\.com/watch\?[=a-z0-9&-]+)#i”,
"",
$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);
}

最简单和最健壮的方法是不使用正则表达式。@FailedDev是否愿意告诉我如何使用(不必是相同的函数)?您正在传递带有$string的部分html,对吗?你是如何得到这个字符串的?我把你的问题读了五遍,脑海中不断涌现出一个问题:“输入字符串是什么?”该功能目前用于用户帖子,以自动嵌入yt视频。我正在尝试使用相同的功能(或逻辑)让用户使用youtube视频作为他们的头像。我一直在网上搜索这个脚本。这一个可以工作,但它只检测内容中的第一个url。例如,我在内容中有3个youtube URL。第一个视频将嵌入,而其他视频仅显示链接。我该怎么办?我知道了!只需将
preg\u match
更改为
preg\u match\u all
。。。万分感谢!要进一步改进这一点,还需要添加https支持:)
(?: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)