PHP-preg_replace不论顺序如何,YouTube都会嵌入 [英] PHP - preg_replace YouTube embed no matter the order
问题描述
我正试图从YouTube嵌入代码中捕获3个元素,但有时这些元素的排列顺序不同,或者有时,嵌入代码包含更多参数.
I'm trying to capture 3 elements from YouTube embed codes but sometimes those elements are not in the same order or sometimes, the embed code contains more parameters.
我想找到一种方法来提取视频ID,宽度和长度,以便为AMP创建YouTube集成.
I'd like to find a way to extract the video ID, the width and length in order to create a YouTube integration for AMP.
嵌入示例:
<iframe width="560" height="315" src="https://www.youtube.com/embed/bpcNPHqs4ng" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
应转换为:
<amp-youtube data-videoid="bpcNPHqs4ng" width="560" height="315"
layout="responsive"></amp-youtube>
如果嵌入始终是相同的,则很容易解决,但是有时嵌入代码从源代码开始,有时从宽度开始,所以...无论我需要用什么顺序来捕获ID,宽度和高度.
If the embed was always the same it would be easy to solve but sometimes the embed code starts with the source, sometimes with the width, ... So whatever the order I would need to capture the ID, the width and the height.
我可以在PHP中使用preg_replace吗?
Can I do this with a preg_replace in PHP ?
我尝试过:
preg_replace('/<iframe width="([0-9]+)" height="([0-9]+)" src="https:\/\/www.youtube.com\/embed\/([A-Za-z0-9]+)" (.*)><\/iframe>/', '<amp-youtube data-videoid="$3" width="$1" height="$2" layout="responsive"></amp-youtube>', $article);
$ article包含使用YouTube嵌入的整篇文章.
$article contains the whole article in which the YouTube embed is used.
如果DOM解析器可以做同样的事情,对我来说也可以,但是我对此不太熟悉.
If a DOM parser can do the same, it's also ok for me but I'm less familiar with this.
谢谢
推荐答案
这是一个 <使用 DOMXPath
搜索具有包含 youtube
的 src
属性的 iframe
标签,然后将其替换为相应的< amp-youtube>
元素:
Here's a DOMDocument
solution to your problem, using DOMXPath
to search for iframe
tags that have a src
attribute that contains youtube
, and then replacing them with a corresponding <amp-youtube>
element:
$doc = new DOMDocument();
$doc->loadHTML($article, LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($doc);
foreach ($xpath->query("//iframe[contains(@src, 'youtube')]") as $youtube) {
// create a new node
$node = $doc->createElement('amp-youtube');
// set attributes
$node->setAttribute('data-videoid', basename(parse_url($youtube->getAttribute('src'), PHP_URL_PATH)));
$node->setAttribute('width', $youtube->getAttribute('width'));
$node->setAttribute('height', $youtube->getAttribute('height'));
$node->setAttribute('layout', 'responsive');
// and now replace the old node
$youtube->parentNode->replaceChild($node, $youtube);
}
echo $doc->saveHTML();
输出(用于我的演示数据):
Output (for my demo data):
<html>
<body>
<div>some text</div>
<iframe name="notyoutube" src="http://example.com"></iframe>
<p>some more text</p>
<amp-youtube data-videoid="bpcNPHqs4ng" width="560" height="315" layout="responsive"></amp-youtube>
<div>one last div</div>
</body>
</html>
这篇关于PHP-preg_replace不论顺序如何,YouTube都会嵌入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!