php - 用于嵌入 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 链接将在文本文件中单独一行。
解决方案
我的猜测是,在这里我们只需要添加一个关闭标签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>
演示
推荐阅读
- symfony - Symfony 5.2 错误:目录“var/cache/dev/jms_serializer”不存在
- sql-server - 约束逻辑和作业
- sql - 有什么方法可以将参数传递给 CTE?
- python - Python鼻子测试:在多个进程中运行测试时不调用自定义插件的添加**挂钩
- python - 获取最大日期并更改数据类型(使用 Python 的 Sqlite)
- spring-boot - 春季 JPQL 处理日期
- javascript - 如何在我的反应 js 页面中显示来自 json 数据的 html 代码?
- python - 如何解决django模型中的循环导入?
- openlayers - OpenLayers 计算两个坐标之间的距离给出了错误的答案
- c - 调用堆栈函数序言混乱