Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 947
Alex Avatar asked Dec 13 '22 06:12

Alex


1 Answers

$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.

like image 129
ThiefMaster Avatar answered Dec 21 '22 23:12

ThiefMaster