Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I want to take a string like this: 'this-is-a-string' and convert it to this: 'thisIsAString':

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
    // Do stuff

    return $string;
}

I need to convert "kebab-case" to "camelCase".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
512 views
Welcome To Ask or Share your Answers For Others

1 Answer

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');

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...