【问题标题】:RegEx for embedding YouTube iframe用于嵌入 YouTube iframe 的正则表达式
【发布时间】:2019-06-02 20:10:41
【问题描述】:
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 链接都将位于文本文件中的单独一行。
【问题讨论】:
标签:
php
regex
preg-replace
regex-lookarounds
regex-group
【解决方案1】:
我的猜测是,在这里我们只需要添加一个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>