Mario Gonzalez Munzon
Mario Gonzalez Munzon

Reputation: 157

Twig - replace string case insensitive

I want to replace a text inside string using twig to make it bold, here's my code:

{{ string|replace({(text): '<span style="font-weight: bold;">'~text~'</span>'})|raw }}

In this example:

string = "Hello world!"
text = "hello"

Will not replace the word 'Hello'. How can I make it to be case insensitive?

Upvotes: 1

Views: 3971

Answers (1)

Alain
Alain

Reputation: 37004

Yes, the replace filter is case sensitive and there are no option to change it.

If you look at Twig's source code, you can see that replace uses strtr:

// lib/Twig/Extension/Core.php
(...)
new Twig_SimpleFilter('replace', 'strtr'),

If you don't care to loose your original case, you can use workarounds, such as:

{{ string|lower|replace({(text): '<span style="font-weight: bold;">'~text~'</span>'})|raw }}

See: http://twigfiddle.com/6ian2b

Else, you can create your own extension, something like:

$filter = new Twig_SimpleFilter('ireplace', function($input, array $replace) {
  return str_ireplace(array_keys($replace), array_values($replace), $input);
});

I think that this feature might be useful for the whole Twig community, you can open an enhancement on GitHub.

Upvotes: 6

Related Questions