ServerSideSkittles ServerSideSkittles - 3 months ago 32
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="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+)?"

Answer

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 }}