将 StudlyCase 和 Snake_case 子字符串转换为“空格单词”,同时保留树枝表达式中的首字母缩略词

问题描述 投票:0回答:4

交响乐树枝

如何仅在小写字母后面添加空格。

{{ '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'.
php symfony replace twig reformatting
4个回答
2
投票

下面的自定义树枝过滤器可以工作!!

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

0
投票

这可以在替换中不使用匹配项来完成。

  • 匹配任意下划线,或者
  • 匹配小写字母,忘记该字母与
    \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}}
)

-1
投票

这是人性化过滤器的片段:

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


-1
投票

我建议你这个Twig Extensions

© www.soinside.com 2019 - 2024. All rights reserved.