Twig - 替换字符串不区分大小写

Mar*_*zon 1 replace case-insensitive twig

我想用twig替换字符串中的文本使其变粗,这是我的代码:

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

在这个例子中:

string = "Hello world!"
text = "hello"
Run Code Online (Sandbox Code Playgroud)

不会取代'你好'这个词.如何使其不区分大小写?

Ala*_*blo 5

是的,replace过滤器区分大小写,没有选项可以更改它.

如果你看一下Twig的源代码,你可以看到它的replace用途strtr:

// lib/Twig/Extension/Core.php
(...)
new Twig_SimpleFilter('replace', 'strtr'),
Run Code Online (Sandbox Code Playgroud)

如果您不想丢失原始案例,可以使用变通办法,例如:

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

请参阅:http://twigfiddle.com/6ian2b

否则,您可以创建自己的扩展,例如:

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

我认为这个功能可能对整个Twig社区有用,你可以在GitHub上打开一个增强功能.