Convert dash to camelCase notation in PHP

PHPz
Release: 2023-08-20 08:34:01
forward
1480 people have browsed it

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');
Copy after login

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');
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!