ReynierPM ReynierPM - 1 month ago 13
PHP Question

How to CamelCase an string value even if string separator is null?

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!

Answer

Use

class UtilString
{
    public function stringToCamelCase($string, $character = null)
    {
        $re = $character == null ? '/^([a-zA-Z])/' : '/(?:^|' . $character . ')([a-zA-Z])/';
        return preg_replace_callback($re, array('UtilString', 'removeCharacterAndCapitalize'), $string);
    }

    private function removeCharacterAndCapitalize($matches)
    {
        return strtoupper($matches[1]);
    }
}

See the PHP demo

Since you need to account for an optional element, you need to use appropriate patterns for both scenarios. $re = $character == null ? '/^([a-zA-Z])/' : '/(?:^|' . $character . ')([a-zA-Z])/'; will specify the first /^([a-zA-Z])/ regex in case the $char is not passed. The second will match at the $char and at the beginning of the string. Both should have the capturing group to be able to change the case and return the proper string inside removeCharacterAndCapitalize.

And as for using a callback itself in your class, you need to check preg_replace_callback requires argument 2 to be a valid callback… Stuck!. It must be defined as array('UtilString', 'removeCharacterAndCapitalize') in the preg_replace_callback.

Comments