Search code examples
phpstringcamelcasing

Convert hyphen delimited string to camelCase?


For example:

abc-def-xyz to abcDefXyz

the-fooo to theFooo

etc.

What's the most efficient way to do this PHP?

Here's my take:

$parts = explode('-', $string);
$new_string = '';

foreach($parts as $part)
  $new_string .= ucfirst($part);

$new_string = lcfirst($new_string);

But i have a feeling that it can be done with much less code :)

ps: Happy Holidays to everyone !! :D


Solution

  • $parts = explode('-', $string);
    $parts = array_map('ucfirst', $parts);
    $string = lcfirst(implode('', $parts));
    

    You might want to replace the first line with $parts = explode('-', strtolower($string)); in case someone uses uppercase characters in the hyphen-delimited string though.