phpregextwigtimber

How do I use RegEx in a Twig/Timber filter?


I'm trying to use preg_replace and a regex to remove the brackets [ and ] and all characters inside of them from the text output of a Twig v2 template using a Twig filter.

An example of the content output by Twig is

An example of content is [caption id="attachment_4487" align="alignright" width="500"] Lorem Ipsum caption blah blah[/caption] and more content.

I want to remove everything inside the [ and ] brackets, leaving the Lorem Ipsum caption blah blah, as well as the An example of content is, etc.

The problem is that right now, I get no content displayed at all when the filter is used. The issue may be the filter construction for Twig; but I get no errors in the log. I've tested the regex at https://regex101.com/r/sN5hYk/1 but that could still be the issue.

The existing Twig filter https://twig.symfony.com/doc/2.x/filters/striptags.html strips html, but doesn't strip brackets.

This is my filter function in functions.php:

add_filter('timber/twig', function($twig) {
   $twig->addExtension(new Twig_Extension_StringLoader());

   $twig->addFilter(
     new Twig_SimpleFilter(
       'strip_square_brackets', 

        function($string) {

            $string = preg_replace('\[.*?\]', '', $string);
            return $string;
}

 )
   );

   return $twig;
});

And the filter is called the standard way in the template.twig file:

{{ content|strip_square_brackets }}


Solution

  • The problem is that you replace a string, not a regex. Of course that string won't match.

    Your line with Regex should look like:

    $string = preg_replace(/\[.*?\]/, '', $string);
    

    Now you're replacing a regex match with the empty string.

    Bonus Edit:

    The answer to your bonus question:

    /\[.*?\].*\[.*?\]/
    

    Basically it just doubles the match and matches everything in between.

    An alternative, which is more robust, if you always use 'caption':

    /\[caption.*/caption\]/