Alex
Alex

Reputation: 67658

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

Upvotes: 4

Views: 2034

Answers (4)

Toni Oriol
Toni Oriol

Reputation: 75

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.

Upvotes: 1

Mark Baker
Mark Baker

Reputation: 212452

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

echo $results;

Upvotes: 2

Calvin Froedge
Calvin Froedge

Reputation: 16373

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);

Upvotes: 1

ThiefMaster
ThiefMaster

Reputation: 318548

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

Upvotes: 9

Related Questions