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 d
Try this:
return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
You're looking for preg_replace_callback, you can use it like this :
$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
return ucfirst($matches[1]);
}, $dashes);
function camelize($input, $separator = '_')
{
return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}
echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
this is my variation on how to deal with it. Here I have two functions, first one camelCase turns anything into a camelCase and it wont mess if variable already contains cameCase. Second uncamelCase turns camelCase into underscore (great feature when dealing with database keys).
function camelCase($str) {
$i = array("-","_");
$str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
$str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
$str = str_replace($i, ' ', $str);
$str = str_replace(' ', '', ucwords(strtolower($str)));
$str = strtolower(substr($str,0,1)).substr($str,1);
return $str;
}
function uncamelCase($str) {
$str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
$str = strtolower($str);
return $str;
}
lets test both:
$camel = camelCase("James_LIKES-camelCase");
$uncamel = uncamelCase($camel);
echo $camel." ".$uncamel;
private function dashesToCamelCase($string)
{
$explode = explode('-', $string);
$return = '';
foreach ($explode as $item) $return .= ucfirst($item);
return lcfirst($return);
}
Here is another option:
private function camelcase($input, $separator = '-')
{
$array = explode($separator, $input);
$parts = array_map('ucwords', $array);
return implode('', $parts);
}