1

I'm looking for some help with replacing YouTube embed codes with something that can be used with AMP pages https://www.ampproject.org/

Example, we would like replace this:

<iframe allowfullscreen="" frameborder="0" height="439" src="https://www.youtube.com/embed/xxxxxxxxxxx" width="780"></iframe>

with this:

<amp-youtube width="480" height="270" layout=responsive data-videoid="xxxxxxxxxxx"></amp-youtube>

Unfortunately, we can't simply replace the iframe tag with amp-youtube because we have other non-YouTube iframes floating around our site. To make things even more complicated, the YouTube embed codes live in our main content area as a WYGWAM field. Obviously, we'd like to also retain the video ID, illustrated above as 'xxxxxxxxxxx'

I've gotten pretty close with using Low Replace but my head can't wrap around regex. Here is the template code for our main content:

{exp:low_replace regex="yes" find='youtube_example' replace='amp_example' multiple="yes"}
    {exp:ce_img:bulk max_width="780" bucket="site" hide_relative_path="yes" attributes='layout="responsive"'}
        {content}
    {/exp:ce_img:bulk}
{/exp:low_replace}

Any help would be much appreciated!

1

Easy peasy, chief. I can't deal with going through the Low Replace docs right now, so you'll have to apply the right parameters, but here you go:

Matching pattern:

<(iframe)(.*)(src=\"https:\/\/www\.youtube\.com\/embed)

Replace pattern:

<amp-iframe$2$3

This will match groups iframe, anything inbetween iframe and the beginning of the src tag, and the then the beginning of the src tag.

I give you a demo (when you click on the link, make sure to switch to preg_replace, not preg_match):

http://www.phpliveregex.com/p/hjP

That should do it, but test it as it might need tweaking.

| improve this answer | |
  • Whoa!!! Thank you thank you thank you!!! I had to tweak it a bit, but it's working now. – ninjaroll Sep 30 '16 at 5:11
  • Oop, yeah I probably didn't read your exact required answer correctly. Derp! But glad I helped! – jrothafer Sep 30 '16 at 17:40
1

Thank you jrothafer for the answer. For those curious, here is the fix. It probably needs some cleaning up, but it's working.

Matching pattern

<(iframe)(.*)(src=\"https:\/\/www\.youtube\.com\/embed)\/(.{11})" width="780"><\/iframe>

Replace pattern

<amp-youtube width="480" height="270" layout="responsive" data-videoid="$4"></amp-youtube>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.