如果在字符串中找到,此功能会嵌入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);
}
Run Code Online (Sandbox Code Playgroud)
Wis*_*guy 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);
}
Run Code Online (Sandbox Code Playgroud)
由于您已经使用第一个查找了URL preg_match(),因此无需运行另一个正则表达式函数来替换它.让它与整个网址匹配,然后简单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)
Run Code Online (Sandbox Code Playgroud)