Reputation: 67658
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
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
Reputation: 212452
$subject = 'abc-def-xyz';
$results = preg_replace_callback ('/-(.)/', create_function('$matches','return strtoupper($matches[1]);'), $subject);
echo $results;
Upvotes: 2
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
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