[Solved] How to perform RegEx using Twig?

Is it possible to regex on a string in twig?

My string is

<a class="twitter-timeline" data-dnt="true" href="https://twitter.com/example" data-widget-id="2374937989837">Tweets by @example</a>
<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

and I want to fetch just the

data-widget-id="2374937989837"

in my template.

The string is outputted as {{ this.theme.twitter }}

I have my regex for this search as

id="d+(.d+)*(,d+)?"

Solution #1:

Write a custom filter for Twig :

<?php
    $filter = new Twig_SimpleFilter('data_widget_id', function ($value) {
        $matches;
        if (preg_match('#data-widget-id="d+(.d+)*(,d+)?"#', $str, $matches)) return $matches[0];
        return $value;
    });

    $twig = new Twig_Environment($loader);
    $twig->addFilter($filter);

And use it in your template :

{{ this.theme.twitter | data_widget_id }}

Solution #2:

Late answer, perhaps useful for others that look at this question

I used the following:

https://github.com/jasny/twig-extensions

That has a.o. a regex filter. Import it using composer or download it, add it to your project using

$twig->addExtension(new JasnyTwigPcreExtension());

And use it as follows:

{{ this.theme.twitter|preg_get('d+(.d+)*(,d+)?') }}

That is it.

As a bonus you get some date, text and array filters.

Respondent: DarkBee

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.