Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing YouTube HTML links with embed code

Tags:

raku

I'm writing web pages in markdown and converting them to HTML using md2html tool. I want to process the output HTML file and find any youtube link like this:

<a href="https://www.youtube.com/watch?v=abcdefgh887">https://www.youtube.com/watch?v=abcdefgh887</a>

and replace it with the embed code:

<iframe width="560" height="315" src="https://www.youtube.com/embed/abcdefgh887?controls=0" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

I toyed around a little with Grammars, mostly to get familiar with them, but concluded this probably isn't the ideal tool for the job. Plus I'd prefer to use existing modules that are easily adaptable to other similar tasks rather than roll my own half-baked solution.

Perl5 has some good tools for this kind of thing but I'd like to use a pure Raku solution so I can learn more Raku.

Any recommendations for good approaches to this problem?

like image 235
StevieD Avatar asked Jul 23 '26 00:07

StevieD


1 Answers

OK, found exactly what I needed for this job with DOM::Tiny.

Use it something like this:

    my $dom = DOM::Tiny.parse($html);
    for $dom.find('a[href]') -> $e  {
        if $e.text ~~ /^https\:\/\/www\.youtube\.com/ {
            my $embed = get_youtube_embed($e.text);
            $e.replace($embed)
        }
    }
like image 74
StevieD Avatar answered Jul 24 '26 22:07

StevieD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!