Edit on GitHub
Jump to docs navigation

Twig Components / Methods / preg_filter

preg_filter(pattern, replacement = "", limit = -1) is a Twig filter to perform a regular expression search and replace, returning only matched subjects (like PHP's preg_filter() function).

preg_filter is identical to preg_replace except it only returns the (possibly transformed) subjects where there was a match.

 {% for item in items|preg_filter('/-test$/', 'invert') %}
    <li>{{ item }}</li>
  {% endfor %}

Jasny's Twig Extensions can be easily installed using Composer:

composer require jasny/twig-extensions


$twig = new Twig_Environment($loader, $options);
$twig->addExtension(new Jasny\Twig\ArrayExtension());

To use in a Symfony project register the extensions as a service:

class: Jasny\Twig\ArrayExtension
- { name: twig.extension }

Source: Jasny

Edit this page on GitHub
Couldn't find what you were looking for? We are happy to help you in the forum, on Slack or on Github.