3v4l.org

run code in 300+ PHP versions simultaneously
<?php $article = '<html><body><div>some text</div><iframe name="notyoutube" src="http://example.com"></iframe><p>some more text</p> <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><div>one last div</div></body></html>'; $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();

preferences:
195.34 ms | 405 KiB | 5 Q