Convert Dashes to CamelCase in PHP

前端 未结 25 1343
南笙
南笙 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:17

    No regex or callbacks necessary. Almost all the work can be done with ucwords:

    function dashesToCamelCase($string, $capitalizeFirstCharacter = false) 
    {
    
        $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
    
        if (!$capitalizeFirstCharacter) {
            $str[0] = strtolower($str[0]);
        }
    
        return $str;
    }
    
    echo dashesToCamelCase('this-is-a-string');
    

    If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.

    Update

    A second parameter was added to ucwords in PHP 5.4.32/5.5.16 which means we don't need to first change the dashes to spaces (thanks to Lars Ebert and PeterM for pointing this out). Here is the updated code:

    function dashesToCamelCase($string, $capitalizeFirstCharacter = false) 
    {
    
        $str = str_replace('-', '', ucwords($string, '-'));
    
        if (!$capitalizeFirstCharacter) {
            $str = lcfirst($str);
        }
    
        return $str;
    }
    
    echo dashesToCamelCase('this-is-a-string');
    

提交回复
热议问题