The regex_replace filter replaces values within a string, or an array of strings, by a regular expression or an array of regular expressions.

{{ 'Make me a kebab string'|lower|regex_replace('/[^\\w]+/', '-') }}


You can pass an array of regular expressions and values to replace.

{{ 'My dog loves yellow FLOWERS and bugs'|regex_replace(['/[a-z]+ow/', '/flowers/i', '/b(.*?)s/i'], ['red', 'leaves', 'balloons']) }}

My dog loves red leaves and balloons

The value to search in can be an array.

{% set original = ['Blue Birds in the spring eat worms from the warm ground', 'red leaves in the fall died on the ground'] %}
{% set new = original|regex_replace(['/blue bird[s+]/i', '/spring/', '/w(.*?)m/', '/[a-z]+ed/', '/ground/'], ['big bear', 'summer', 'corn', 'dead', 'trees']) %}

The new variable in the above example will have a value of

    0 => big bear in the summer eat corns from the corn trees
    1 => dead leaves in the fall dead on the trees


The regex_replace filter has the following signature.

regex_replace(pattern, replace)

Argument 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.

{{ 'Christmas this year is 12/25/2010'|regex_replace('/(\\d{2}\\/\\d{2}\\/)(\\d{4})/', '${1}' ~ }}

< Back to the list of filters