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
$stringWithDash = 'Pending-Seller-Confirmation';
$camelize = str_replace('-', '', ucwords($stringWithDash, '-'));
echo $camelize;
output: PendingSellerConfirmation
ucwords
second(optional) parameter helps in identify a separator to camelize the string.
str_replace
is used to finalize the output by removing the separator.
Here is a small helper function using a functional array_reduce approach. Requires at least PHP 7.0
private function toCamelCase(string $stringToTransform, string $delimiter = '_'): string
{
return array_reduce(
explode($delimiter, $stringToTransform),
function ($carry, string $part): string {
return $carry === null ? $part: $carry . ucfirst($part);
}
);
}
I would probably use preg_replace_callback(), like this:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
}
function removeDashAndCapitalize($matches) {
return strtoupper($matches[0][1]);
}
function camelCase($text) {
return array_reduce(
explode('-', strtolower($text)),
function ($carry, $value) {
$carry .= ucfirst($value);
return $carry;
},
'');
}
Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...
This is simpler :
$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );
One liner, PHP >= 5.3:
$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));