Home  >  Article  >  Backend Development  >  Convert dash to camelCase notation in PHP

Convert dash to camelCase notation in PHP

PHPz
PHPzforward
2023-08-20 08:33:461451browse

Convert dash to camelCase notation in PHP

The following is the PHP code to convert dashes to camelCase −

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

Example output − thisIsATestString

Note − There is no need to use regular expressions or callback functions, it can be implemented using the ucwords function.

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

The above is the detailed content of Convert dash to camelCase notation in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete