views:

102

answers:

4

Can someone help me complete this PHP function? I want to take a string like this: 'this-is-a-string' and convert it to this: 'thisIsAString':

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
    // Do stuff


    return $string;
}
+2  A: 
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
    if( $first ) {
        $first = false;
        continue;
    }
    $v = ucfirst( $v );
}
return implode( "", $string );

Untested code. Check the PHP docs for the functions im-/explode and ucfirst.

svens
+1  A: 

I would probably use preg_replace_callback(), like this:

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
  return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
}

function removeDashAndCapitalize($matches) {
  return strtoupper($matches[0][1]);
}
yjerem
+7  A: 

No regex or callbacks necessary. Almost all the work can be done with ucwords:

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) 
{

    $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));

    if (!$capitalizeFirstCharacter) {
        $str[0] = strtolower($str[0]);
    }

    return $str;
}

echo dashesToCamelCase('this-is-a-string');

If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.

webbiedave
A: 

Try this:

 return preg_replace("/\-(.)/e", "strtoupper(\\1)", $string);
Jakub Hampl