Convert Dashes to CamelCase in PHP

前端 未结 25 1336
南笙
南笙 2020-12-07 19:40

Can someone help me complete this PHP function? I want to take a string like this: \'this-is-a-string\' and convert it to this: \'thisIsAString\':

function d         


        
25条回答
  •  甜味超标
    2020-12-07 20:28

    Many good solutions above, and I can provide a different way that no one mention before. This example uses array. I use this method on my project Shieldon Firewall.

    /**
     * Covert string with dashes into camel-case string.
     *
     * @param string $string A string with dashes.
     *
     * @return string
     */
    function getCamelCase(string $string = '')
    {
        $str = explode('-', $string);
        $str = implode('', array_map(function($word) {
            return ucwords($word); 
        }, $str));
    
        return $str;
    }
    

    Test it:

    echo getCamelCase('This-is-example');
    

    Result:

    ThisIsExample
    

提交回复
热议问题