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:
this is my variation on how to deal with it. Here I have two functions, first one camelCase turns anything into a camelCase and it wont mess if variable already contains cameCase. Second uncamelCase turns camelCase into underscore (great feature when dealing with database keys).
function camelCase($text) {
return array_reduce(
explode('-', strtolower($text)),
function ($carry, $value) {
$carry .= ucfirst($value);
return $carry;
},
'');
}
Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...
The TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.
To use it, import the phar file to your project and:
use org\turbocommons\src\main\php\utils\StringUtils;
echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);
// will output 'sNakeCase'
ucwords second(optional) parameter helps in identify a separator to camelize the string.
str_replace is used to finalize the output by removing the separator.
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;
}