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 d
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:
use org\turbocommons\src\main\php\utils\StringUtils;
echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);
// will output 'sNakeCase'
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
In Laravel use Str::camel()
use Illuminate\Support\Str;
$converted = Str::camel('foo_bar');
// fooBar
If you use Laravel framework, you can use just camel_case() method.
camel_case('this-is-a-string') // 'thisIsAString'
No regex or callbacks necessary. Almost all the work can be done with ucwords:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirstCharacter) {
$str[0] = strtolower($str[0]);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.
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:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
Overloaded one-liner, with doc block...
/**
* Convert underscore_strings to camelCase (medial capitals).
*
* @param {string} $str
*
* @return {string}
*/
function snakeToCamel ($str) {
// Remove underscores, capitalize words, squash, lowercase first.
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}
Try this:
$var='snake_case';
echo ucword($var,'_');
Output:
Snake_Case remove _ with str_replace