Convert Dashes to CamelCase in PHP

PHPServer Side ProgrammingProgramming

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'.

raja
Published on 06-Apr-2020 07:37:52
Advertisements