phpsymfonyreplacetwigreformatting

Convert StudlyCase and snake_case substrings to "spaced words" while preserving acronyms within twig expressions


Symfony twig

How to add space following capital letters only when it is following small letters.

{{ 'IWantHTML'|humanize }} //displays 'I want h t m l'. // it should be 'I want HTML'.

The other thing is it makes everything small letters following the first letter. e.x.

{{ 'IWantHTML'|humanize }} // should be 'I Want HTML'.
{{ 'i_want_html'|humanize}} // should be 'I want html'.
{{ 'CustomerPickSale2'|humanize}} // should be 'Customer Pick Sale2'.

Solution

  • Below custom twig filter works!!

    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