DrupalX

Extension
Framework

Regular expressions

DrupalX adds regular expression support in Twig. Regular expressions are enclosed by inverted apostrophes and can be used as arguments for various functions. Even some regular Twig functions like "replace" are overloaded by DrupalX to seamlessly accept these new expressions:

{{ "Doe, John" | replace(`(.*),(.*)`,'$2 $1') }}

This example will print - you might have guessed it:

John Doe

To find out what exactly has been matched by a certain regular expression you can use DrupalX's match filter:

{{ "Area 51" | match(`(\d+$)`) }}

The match filter will always return the first capture group (i.e. the first expression in parentheses):

51

If there are no capture groups, it will return the whole expression if matched. The previous example can thus be written even shorter:

{{ "Area 51" | match(`\d+$`) }}