Convert string with dashes to camelCase

Solution 1:

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

Solution 2:

This can be done very simply, by using ucwords which accepts delimiter as param:

function camelize($input, $separator = '_')
{
    return str_replace($separator, '', ucwords($input, $separator));
}

NOTE: Need php at least 5.4.32, 5.5.16

Solution 3:

Overloaded one-liner, with doc block...

/**
 * Convert underscore_strings to camelCase (medial capitals).
 *
 * @param {string} $str
 *
 * @return {string}
 */
function snakeToCamel ($str) {
  // Remove underscores, capitalize words, squash, lowercase first.
  return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}