How to convert this type of php string to camel case?
$string = primary-getallgroups-sys
I've tried but just found different solutions to camelize a string with spaces. Like ucword($string), but it just capitalize the first word. When i add a delimeter of hyphen (-), it gives error.
$string = 'primary-getallgroups-sys';
// split string by '-'
$words = explode('-', $string);
// make a strings first character uppercase
$words = array_map('ucfirst', $words);
// join array elements with '-'
$string = implode('-', $words);
echo $string; // is now Primary-Getallgroups-Sys
You can make a function to convert these types of string to camel cases.
Try this:
<?php
// CONVERT STRING TO CAMEL CASE SEPARATED BY A DELIMITER
function convertToCamel($str, $delim){
$exploded_str = explode($delim, $str);
$exploded_str_camel = array_map('ucwords', $exploded_str);
return implode($delim, $exploded_str_camel);
}
$string = 'primary-getallgroups-sys';
echo convertToCamel($string, '-'); // Answer
?>
In fact camel case is more like this: iAmCamelCased
.
And this is mixed case: IAmMixedCased
.
@sundas-mushtaq Also note that hyphens will break your code if used in symbol names (like in functions or variables).
To camelize, use this:
function camelize($word, $delimiter){
$elements = explode($delimiter, $word);
for ($i = 0; $i < count($elements); $i++) {
if (0 == $i) {
$elements[$i] = strtolower($elements[$i]);
} else {
$elements[$i] = strtolower($elements[$i]);
$elements[$i] = ucwords($elements[$i]);
}
}
return implode('', $elements);
}
And to mixify, use this :
function mixify($word, $delimiter){
$word = strtolower($word);
$word = ucwords($word, $delimiter);
return str_replace($delimiter, '', $word);
}
From Symfony
function camelize(string $string): string
{
return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $string))));
}