交响乐树枝
如何仅在小写字母后面添加空格。
{{ 'IWantHTML'|humanize }} //displays 'I want h t m l'. // it should be 'I want HTML'.
另一件事是它使第一个字母后面的所有内容都变成小字母。 例如
{{ 'IWantHTML'|humanize }} // should be 'I Want HTML'.
{{ 'i_want_html'|humanize}} // should be 'I want html'.
{{ 'CustomerPickSale2'|humanize}} // should be 'Customer Pick Sale2'.
下面的自定义树枝过滤器可以工作!!
new Twig_SimpleFilter('readable', array($this, 'readableFormat'))
/**
* @param $string
* @return mixed
*/
public function readableFormat($string)
{
$match_filter = array(
'/(?<!\ )[A-Z][a-z]+/',
'/(?<!\ )[A-Z][A-Z]+/',
);
$Words = preg_replace($match_filter, ' $0', trim($string));
return str_replace('_', ' ', $Words);
}
{{ 'IWantHTML'|readable }} // I Want HTML
{{ 'i_want_html'|readable|ucfirst }} // I want html
{{ 'CustomerPickSale2'|readable|ucfirst }} // Customer Pick Sale2
这可以在替换中不使用匹配项来完成。
\K
,向前查找大写字母,或者 \K
,向前查找大写字母后跟小写字母代码:(演示)
$tests = [
"{{ 'IWantHTML'|humanize }}", // should be 'I Want HTML'.
"{{ 'i_want_html'|humanize}}", // should be 'I want html'.
"{{ 'CustomerPickSale2'|humanize}}", // should be 'Customer Pick Sale2'
];
print_r(
preg_replace('/_|[a-z]\K(?=[A-Z])|[A-Z]\K(?=[A-Z][a-z])/', ' ', $tests)
);
输出:
Array
(
[0] => {{ 'I Want HTML'|humanize }}
[1] => {{ 'i want html'|humanize}}
[2] => {{ 'Customer Pick Sale2'|humanize}}
)
这是人性化过滤器的片段:
function humanize($str) {
$str = trim(strtolower($str));
$str = preg_replace('/[^a-z0-9\s+]/', '', $str);
$str = preg_replace('/\s+/', ' ', $str);
$str = explode(' ', $str);
$str = array_map('ucwords', $str);
return implode(' ', $str);
}
你可以看到它没有做你想要的事情。所以你必须实现自己的过滤器如何编写Twig扩展以及如何创建自定义Twig Fitler
我建议你这个Twig Extensions