4

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

Alex
  • 66,732
  • 177
  • 439
  • 641

4 Answers4

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

ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
2
$subject = 'abc-def-xyz';
$results = preg_replace_callback ('/-(.)/', create_function('$matches','return strtoupper($matches[1]);'), $subject);

echo $results;
Mark Baker
  • 209,507
  • 32
  • 346
  • 385
1
str_replace('-', '', lcfirst(ucwords('foo-bar-baz', '-'))); // fooBarBaz

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

Toni Oriol
  • 75
  • 2
  • 8
1

If that works, why not use it? Unless you're parsing a ginormous amount of text you probably won't notice the difference.

The only thing I see is that with your code the first letter is going to get capitalized too, so maybe you could add this:

foreach($parts as $k=>$part)
  $new_string .= ($k == 0) ? strtolower($part) : ucfirst($part);
Calvin Froedge
  • 16,135
  • 16
  • 55
  • 61