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应该在其上显示的网页的查看源时,只会得到以下网址。
https://www.youtube.com/qvuvjEkeDAw
无法看到iframe代码。
每个youtube链接将在文本文件中单独显示。
答案 0 :(得分:0)
我的猜测是,在这里我们只需要添加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>