'Camelize a php string
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.
Solution 1:[1]
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
?>
Solution 2:[2]
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);
}
Solution 3:[3]
From Symfony
function camelize(string $string): string
{
return lcfirst(str_replace(' ', '', ucwords(preg_replace('/[^a-zA-Z0-9\x7f-\xff]++/', ' ', $string))));
}
Solution 4:[4]
// if you want to camelize first word also, remove lcfirst call
function camelize($string) {
$tokens = array_map("ucFirst", explode("_", $string)) ;
return lcfirst(implode("",$tokens));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ashish Choudhary |
| Solution 2 | Daishi |
| Solution 3 | Handsome Nerd |
| Solution 4 | Gio904 |
