ServerSideSkittles ServerSideSkittles - 7 months ago 77
Twig Question

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="" 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.src=p+"://";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>

and I want to fetch just the


in my template.

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

I have my regex for this search as



Write a custom filter for Twig :

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

    $twig = new Twig_Environment($loader);

And use it in your template :

{{ this.theme.twitter | data_widget_id }}