3

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!

ReynierPM
  • 17,594
  • 53
  • 193
  • 363

2 Answers2

3

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.

Community
  • 1
  • 1
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
1

PHP has a function called ucwords() that uppercases the first character of every word. It takes a second parameter for the delimiters.

Note that ucwords() does not remove the delimiters. So you need to do this by yourself, e.g. with str_replace. Here is a simple example:

function stringToCamelCase($string) {

    $delimiters = array('_');

    $string = ucwords($string, implode('', $delimiters));
    $string = str_replace($delimiters, '', $string);

    return $string;
}

$my_string = 'string_with_separator';
echo stringToCamelCase($my_string);

Output:

StringWithSeparator
simon
  • 2,896
  • 1
  • 17
  • 22