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
here is very very easy solution in one line code
$string='this-is-a-string' ;
echo str_replace('-', '', ucwords($string, "-"));
output ThisIsAString
This function is similar to @Svens's function
function toCamelCase($str, $first_letter = false) {
$arr = explode('-', $str);
foreach ($arr as $key => $value) {
$cond = $key > 0 || $first_letter;
$arr[$key] = $cond ? ucfirst($value) : $value;
}
return implode('', $arr);
}
But clearer, (i think :D) and with the optional parameter to capitalize the first letter or not.
Usage:
$dashes = 'function-test-camel-case';
$ex1 = toCamelCase($dashes);
$ex2 = toCamelCase($dashes, true);
var_dump($ex1);
//string(21) "functionTestCamelCase"
var_dump($ex2);
//string(21) "FunctionTestCamelCase"
Another simple approach:
$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));
Many good solutions above, and I can provide a different way that no one mention before. This example uses array. I use this method on my project Shieldon Firewall.
/**
* Covert string with dashes into camel-case string.
*
* @param string $string A string with dashes.
*
* @return string
*/
function getCamelCase(string $string = '')
{
$str = explode('-', $string);
$str = implode('', array_map(function($word) {
return ucwords($word);
}, $str));
return $str;
}
Test it:
echo getCamelCase('This-is-example');
Result:
ThisIsExample
This can be done very simply, by using ucwords which accepts delimiter as param:
function camelize($input, $separator = '_')
{
return str_replace($separator, '', ucwords($input, $separator));
}
NOTE: Need php at least 5.4.32, 5.5.16
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
if( $first ) {
$first = false;
continue;
}
$v = ucfirst( $v );
}
return implode( "", $string );
Untested code. Check the PHP docs for the functions im-/explode and ucfirst.