Convert hyphen delimited string to camelCase?

For instance:

abc-def-xyz to abcDefXyz

the-fooo to theFooo

and etc.

What is the most efficient way to do this php?

Here is my trick:

 $parts = explode('-', $string); $new_string = ''; foreach($parts as $part) $new_string .= ucfirst($part); $new_string = lcfirst($new_string); 

But I have a feeling that this can be done with much less code :)

ps: Happy holidays to everyone !: D

+4
source share
4 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)); if someone uses uppercase characters in a hyphen-delimited string.

+8
source
 $subject = 'abc-def-xyz'; $results = preg_replace_callback ('/-(.)/', create_function('$matches','return strtoupper($matches[1]);'), $subject); echo $results; 
+2
source

If this works, why not use it? If you don't parse a lot of text, you probably won't notice the difference.

The only thing I see is that with your code the first letter will also be capitalized, so maybe you can add this:

 foreach($parts as $k=>$part) $new_string .= ($k == 0) ? strtolower($part) : ucfirst($part); 
+1
source
 str_replace('-', '', lcfirst(ucwords('foo-bar-baz', '-'))); // fooBarBaz 

ucwords accepts the word separator as the second parameter, so we only need to pass a hyphen, and then write the first letter with lcfirst and finally remove all hyphens with str_replace .

+1
source

Source: https://habr.com/ru/post/1387956/


All Articles