1

I'm replacing all ocurrences in a string to . And I'm doing:

1) I get video_id from youtube url.

preg_match('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);

2) I remove iframe with amp-youtube adding the url video id.

$string = preg_replace( '/<iframe\s+.*?\s+src=(".*?").*?<\/iframe>/',
                    '<amp-youtube data-videoid="'.$video_id[1].'" width="480" height="270" layout="responsive"></amp-youtube>', (str_replace("https://www.youtube.com/embed/","", $string)));

That works fine for just one ocurrence.

But If I have more than one iframe... Ok I can do

preg_match_all('/embed\/([\w+\-+]+)[\"\?]/', $string,$video_id);

to get all video ids in the string.

But how can I loop to add each id to every amp-youtube data-videoid in a string??

Thanks!!

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
heavy_hd
  • 25
  • 2

1 Answers1

0

I wish you would have posted a minimal sample html string and your expected output, but I think I gather your meaning.

Don't use regex to parse html. Iterate while there is an existing iframe tag and replace it with your desired tag using the prepared substring from the iframe's src value.

Code: (Demo)

$html = <<<HTML
<div>
  <p>
    <iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/sNEJOm4hSaw" width="640"></iframe>
  </p>
  <p>
    <iframe allowfullscreen="" class="media-element file-default" data-fid="2219" data-media-element="1" frameborder="0" height="360" src="https://www.youtube.com/embed/abcdefghijk" width="640"></iframe>
  </p>
</div>
HTML;

$dom = new DOMDocument;
$dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
while ($iframe = $dom->getElementsByTagName('iframe')->item(0)) {
    $amp = $dom->createElement('amp-youtube');
    $amp->setAttribute('width', '480');
    $amp->setAttribute('height', '270');
    $amp->setAttribute('layout', 'responsive');
    $amp->setAttribute('data-videoid', str_replace("https://www.youtube.com/embed/","", $iframe->getAttribute('src')));
    $iframe->parentNode->replaceChild($amp, $iframe);
}
echo $dom->saveHTML();

Output:

<div>
  <p>
    <amp-youtube width="480" height="270" layout="responsive" data-videoid="sNEJOm4hSaw"></amp-youtube>
  </p>
  <p>
    <amp-youtube width="480" height="270" layout="responsive" data-videoid="abcdefghijk"></amp-youtube>
  </p>
</div>
mickmackusa
  • 43,625
  • 12
  • 83
  • 136