Home > front end >  How to use regex in Grav regex_replace() function
How to use regex in Grav regex_replace() function

Time:07-24

Their example by the link https://learn.getgrav.org/17/themes/twig-tags-filters-functions/functions#regex-replace works.

But something like

{% set result = regex_replace('The quick brown fox', ['/(\s)?/'], ['']) %}
{{ result }}

does not work - the string is not changed

How to use regex in their wrapper?

CodePudding user response:

Update:

Sorry I've overlooked the link in your question.

Try to escape the backslash. See this issue on regex_replace.

The following works fine:

{% set result = regex_replace('The quick brown fox', ['/(\\s)?/'], ['']) %}
{{ result }}

Result: Thequickbrownfox

Btw: The parenthesis and question mark are not necessary in your example.

Original:

Grav adds a custom filter for this. See https://learn.getgrav.org/17/themes/twig-tags-filters-functions/filters#regex-replace.

It's a wrapper around PHP's preg_replace().

Example:

'The quick brown fox jumps over the lazy dog.' | regex_replace(['/quick/','/brown/','/fox/','/dog/'], ['slow','black','bear','turtle'])

which yields:

The slow black bear jumps over the lazy turtle.
  • Related