PHP - preg_replace YouTube无论订单如何嵌入

问题描述 投票:0回答:1

我正在尝试从YouTube嵌入代码中捕获3个元素,但有时这些元素的顺序不同,或者有时,嵌入代码包含更多参数。

我想找到一种方法来提取视频ID,宽度和长度,以便为AMP创建YouTube集成。

嵌入示例:

<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,宽度和高度。

我可以用PHP中的preg_replace做到这一点吗?

我试过这个:

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嵌入的整篇文章。

如果一个DOM解析器可以做同样的事情,它也适合我,但我对此不太熟悉。

谢谢

php preg-replace amp-html domparser
1个回答
2
投票

这是你的问题的DOMDocument解决方案,使用DOMXPath搜索具有包含iframesrc属性的youtube标签,然后用相应的<amp-youtube>元素替换它们:

$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();

输出(对于我的演示数据):

<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>

Demo on 3v4l.org

© www.soinside.com 2019 - 2024. All rights reserved.