I need to convert a given string value (with or without separator) into a CamelCase
string. So far this is what I am doing:
class UtilString
{
public function stringToCamelCase($string, $character = null)
{
return preg_replace_callback("/{$character}[a-zA-Z]/", 'removeCharacterAndCapitalize', $string);
}
private function removeCharacterAndCapitalize($matches)
{
return strtoupper($matches[0][1]);
}
}
$str1 = 'string_with_separator';
$str2 = 'string';
$test1 = (new UtilString())->stringToCamelCase($str1, '_');
$test2 = (new UtilString())->stringToCamelCase($str2);
Having the code above the outputs are:
$test1 = 'string_with_separator';
$test2 = 'string';
I want them to be:
$test1 = 'StringWithSeparator';
$test2 = 'String';
How? What I am doing wrong and how to fix it? I am using PHP 5.5.x!
NOTE: if you know any string manipulation class|package with this type of function please let me know so I am not reinventing the wheel!