Sem regex ou callbacks necessários. Quase todo o trabalho pode ser feito com 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');
Se estiver usando PHP> = 5.3, você pode usar lcfirst em vez de strtolower.
Atualizar
Um segundo parâmetro foi adicionado ao ucwords no PHP 5.4.32 / 5.5.16 o que significa que não precisamos primeiro mudar os travessões para espaços (graças a Lars Ebert e PeterM por apontar isso). Aqui está o código atualizado:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
if (!$capitalizeFirstCharacter) { $str = lcfirst($str); }