Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert string with dashes to camelCase

Tags:

string

php

I want to take a string like this: 'this-is-a-string' and convert it to this: 'thisIsAString':

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {     // Do stuff      return $string; } 

I need to convert "kebab-case" to "camelCase".

like image 265
Kirk Ouimet Avatar asked May 07 '10 22:05

Kirk Ouimet


People also ask

What is CamelCase conversion?

Camel case (sometimes stylized as camelCase or CamelCase, also known as camel caps or more formally as medial capitals) is the practice of writing phrases without spaces or punctuation. It indicates the separation of words with a single capitalized letter, and the first word starting with either case.

What is CamelCase example?

Meaning of camel case in English. the use of a capital letter to begin the second word in a compound name or phrase, when it is not separated from the first word by a space: Examples of camel case include "iPod" and "GaGa".


1 Answers

No regex or callbacks necessary. Almost all the work can be done with ucwords:

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

If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.

Update

A second parameter was added to ucwords in PHP 5.4.32/5.5.16 which means we don't need to first change the dashes to spaces (thanks to Lars Ebert and PeterM for pointing this out). Here is the updated code:

function dashesToCamelCase($string, $capitalizeFirstCharacter = false)  {      $str = str_replace('-', '', ucwords($string, '-'));      if (!$capitalizeFirstCharacter) {         $str = lcfirst($str);     }      return $str; }  echo dashesToCamelCase('this-is-a-string'); 
like image 75
webbiedave Avatar answered Oct 05 '22 20:10

webbiedave