How to String of Text to camelCase in PHP

To make a string of text camel-cased in PHP, we can write a function that will uppercase the first character of each word, replace dashes and whitespaces with nothing and convert the first character to lowercase.

 

function toCamelCase($string, $capitalizeFirstChar = false)
{

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

  if (!$capitalizeFirstChar) {
    $str = lcfirst($str);
  }

  return $str;
}


public function handle()
{
  $string = 'This is a string-of-text';

  $output = $this->toCamelCase($string);

  print($output);
}
thisIsAStringOfText