php – 使用HTML嵌入代码替换文本中的YouTube URL
发布时间:2020-12-13 22:39:09 所属栏目:PHP教程 来源:网络整理
导读:如果在字符串中找到,此功能会嵌入youtube视频. 我的问题是什么是最简单的方法来捕获嵌入的视频(iframe,只有第一个,如果还有更多)并忽略其余的字符串. function youtube($string,$autoplay=0,$width=480,$height=390){preg_match('#(v/|watch?v=)([w-]+)#
如果在字符串中找到,此功能会嵌入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网址,并将其替换为实际的视频嵌入代码.
这是我修改它的方式: function youtube($string,$height=390) { preg_match('#(?:http://)?(?:www.)?(?:youtube.com/(?:v/|watch?v=)|youtu.be/)([w-]+)(?:S+)?#',$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,然后执行整个匹配的简单str_replace()($match [0]).视频代码在第一个子模式中捕获($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) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |