2

I need to take the dominant YouTube URL schemas and convert them into a YouTube embed URL of the form:

https://www.youtube.com/embed/VIDEOID

I know there are technically loads of possible YouTube URL variants but I'm really only interested in:

  1. https://www.youtube.com/watch?v=MvqY2NcBWI8
  2. https://youtu.be/MvqY2NcBWI8

…where either of those could be extended with optional parameters.

So I'm doing this to extract the vidId, which works for 1:

{% set vidUrl = block.videoUrl %}
{% set vidId  = vidUrl|replace('/^http.*\\?v=([^\\&]+)(\\&.*)?$/', '$1') %}

…and then this for 2:

{% set vidId = vidId ? vidId : vidUrl|replace('/^http.*\\.be\\/([^\\?]+)(\\?.*)?$/', '$1') %}

…which doesn’t work.

And yet when I replace \\ with \ and test it in my text editor it does work.

This should capture the id up to the beginning of any query string…

([^\\?]+)

…and this should discard any parameters which follow…

(\\?.*)?$

Shouldn't it? What am I missing?

1 Answer 1

2

Doh! It was my ternary logic that was failing not the regex. I’m now doing this:

{% set vidUrl = block.videoUrl %}

{% if 'youtu' in vidUrl %}
    {# Check for an 'embed' URL which may need cleaning #}
    {% set vidId = 'embed' in vidUrl ? vidUrl|replace('/^http.*embed\\/([^\\?]+)(\\?.*)?$/', '$1') : null %}

    {# Check for a 'watch' URL which may need cleaning #}
    {% set vidId = 'watch' in vidUrl ? vidUrl|replace('/^http.*\\?v=([^\\&]+)(\\&.*)?$/', '$1') : vidId %}

    {# Check for a 'youtu.be' URL which may need cleaning #}
    {% set vidId = '.be/' in vidUrl ? vidUrl|replace('/^http.*\\.be\\/([^\\?]+)(\\?.*)?$/', '$1') : vidId %}

    {% set srcUrl = vidId ? "https://www.youtube.com/embed/#{vidId}" : null %}
{% endif %}

{% if srcUrl %}
    {# Write the iframe #}
{% else %}
    {# Write some help for logged in CMS folks #}
{% endif %}
2
  • 1
    Maybe in your case it's overkill, but a custom Twig variable would be perfect for this job. Also the oEmbed plugin is good at this.
    – gioppe
    Commented Jul 20, 2021 at 12:10
  • Thanks @gioppe, oEmbed does look like a cool plugin. I will check it out. Commented Jul 21, 2021 at 11:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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