首页 > 解决方案 > 用于嵌入 YouTube iframe 的正则表达式

问题描述

PHP代码:

$patterny = '/(.*) ((youtube.com) | (youtu.be) | (www.youtube.com)) (.*)/i';

$replacementy = '<iframe src="http://youtube.com/$6" allowfullscreen></iframe>';

$string2 = preg_replace($patterny, $replacementy, $string);

echo $string2;

我在http://regex101.com中测试了上述正则表达式,它的输出令人满意。

https://regex101.com/r/wqbywv/1

当我查看 iframe 应在其上显示的网页的视图源时,我只得到以下 URL。

https://www.youtube.com/qvuvjEkeDAw

iframe 代码无处可见。

每个 youtube 链接将在文本文件中单独一行。

标签: phpregexpreg-replaceregex-lookaroundsregex-group

解决方案


我的猜测是,在这里我们只需要添加一个关闭标签i中缺少的内容。iframe此外,如果我们愿意,我们可以修改和简化我们的表达式:

测试

$re = '/(.*) ((youtube.com) | (youtu.be) | (www.youtube.com) ) (.*)/mix';
$str = 'http://youtu.be/cCnrX1w5luM
www.youtube.com/cCnrX1w5luM
youtu.be/cCnrX1w5luM
https://www.youtube.com/watch?v=nzj7Wg4DAbs
http://www.youtube.com/watch?v=nzj7Wg4DAbs
youtube.com/watch?v=nzj7Wg4DAbs
http://www.youtube.com/watch?v=-wtIMTCHWuI
http://www.youtube.com/v/-wtIMTCHWuI?version=3&autohide=1
http://youtu.be/-wtIMTCHWuI
http://www.youtube.com/oembed?url=http%3A//www.youtube.com/watch?v%3D-wtIMTCHWuI&format=json
Hello https://www.youtube.com/watch?v=nzj7Wg4DAbs world
';
$subst = '<iframe src="htpp://youtube.com$6" allowfullscreen></iframe>';

$result = preg_replace($re, $subst, $str);

echo $result;

输出

<iframe src="htpp://youtube.com/cCnrX1w5luM" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/cCnrX1w5luM" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/cCnrX1w5luM" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/watch?v=nzj7Wg4DAbs" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/watch?v=nzj7Wg4DAbs" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/watch?v=nzj7Wg4DAbs" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/watch?v=-wtIMTCHWuI" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/v/-wtIMTCHWuI?version=3&autohide=1" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/-wtIMTCHWuI" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/watch?v%3D-wtIMTCHWuI&format=json" allowfullscreen></iframe>
<iframe src="htpp://youtube.com/watch?v=nzj7Wg4DAbs world" allowfullscreen></iframe>

演示


推荐阅读