Convert Dashes to CamelCase in PHP


Following is the code to convert dashes to CamelCase in PHP −

Sample input − this-is-a-test-string

Sample output − thisIsATestString

Note − There is no need to use regex or callbacks. It can be achieved using ucwords.

function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
   $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
   if (!$capitalizeFirstCharacter) {
      $str[0] = strtolower($str[0]);
   }
   return $str;
}
echo dashToCamelCase('this-is-a-string');

For PHP version>=5.3, the below code can be used −

function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
   $str = str_replace('-', '', ucwords($string, '-'));
   if (!$capitalizeFirstCharacter) {
      $str = lcfirst($str);
   }
   return $str;
echo dashToCamelCase('this-is-a-test-string');

The 'lcfirst' function needs to be used instead of 'strtolower'.

Updated on: 06-Apr-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements