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

时间:2015-02-25 13:18:48

标签: replace twig case-insensitive

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

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

在这个例子中:

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

不会取代“你好”这个词。如何使其不区分大小写?

1 个答案:

答案 0 :(得分:5)

是的,replace过滤器区分大小写,无法更改它。

如果您查看Twig的源代码,可以看到replace使用strtr

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

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

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

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

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

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

我认为此功能可能对整个Twig社区有用,您可以在GitHub上打开增强功能。