The regex_filter replaces values within a string by a regular expression and returns only the (possibly transformed) subjects where there was a match.

It's only useful when doing a replacement on an array of values. If you use this with a string then the entire string is returned and it's essentially the same as the regex_replace filter.

{% set new = ['x', 'y', 'z', 'm', 'e', '3', '10']|regex_filter(['/\\d/', '/[x-z]/'], ['$0 is a NUMBER ', '$0 is a LETTER ']) %}

The above example would return the following array:

    [0] => x is a LETTER
    [1] => y is a LETTER
    [2] => z is a LETTER
    [5] => 3 is a NUMBER
    [6] => 1 is a NUMBER 0 is a NUMBER

"m" and "e" values are not returned as they didn't match any of the patterns.


The regex_filter filter has the following signature.

regex_filter(pattern, replace)

Arguments Description

The regular expression to match or an array of regular expressions to match.


['/[c-m]+/', '/\\d+/']

Any backslashes in the regular expression need to be double escaped like this: \\


The value to replace the pattern with or an array of values to replace the pattern with.

If replace is a string and the pattern argument is an array, all matched patterns will be replaced by that string.

If both replace and pattern and are arrays, then each pattern will be replaced by the replacement counterpart. If there are fewer elements in the replace array than in the pattern array, then any extra patterns will be replaced by an empty string.

You can reference grouped matches by using this format: $n. Each backreference will be replaced by the text captured by the n'th parenthesized pattern. n can be from 0 to 99, and $0 refers to the text matched by the whole pattern. Parentheses patterns are counted from left to right (starting from 1) to obtain the number of the capturing subpattern.

If you have a number immediately following your backreference then you would wrap the number for the reference in curly brackets like this: ${1}6 where "1" is the reference number and "6" is just the number in the replacement string.

< Back to the list of filters