Question

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

Was it helpful?

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.

OTHER TIPS

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

echo $results;

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top