Can someone help me complete this PHP function? I want to take a string like this: 'this-is-a-string' and convert it to this: 'thisIsAString':
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
// Do stuff
return $string;
}
Try this:
Output:
No regex or callbacks necessary. Almost all the work can be done with ucwords:
If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.
Update
A second parameter was added to ucwords in PHP 5.4.32/5.5.16 which means we don't need to first change the dashes to spaces (thanks to Lars Ebert and PeterM for pointing this out). Here is the updated code:
The TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.
https://github.com/edertone/TurboCommons
To use it, import the phar file to your project and:
Here's the link to the method source code:
https://github.com/edertone/TurboCommons/blob/b2e015cf89c8dbe372a5f5515e7d9763f45eba76/TurboCommons-Php/src/main/php/utils/StringUtils.php#L653
$stringWithDash = 'Pending-Seller-Confirmation'; $camelize = str_replace('-', '', ucwords($stringWithDash, '-')); echo $camelize;
output: PendingSellerConfirmationucwords
second(optional) parameter helps in identify a separator to camelize the string.str_replace
is used to finalize the output by removing the separator.Overloaded one-liner, with doc block...
Here is another option: