115

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

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Kirk Ouimet
  • 27,280
  • 43
  • 127
  • 177

30 Answers30

228

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');
webbiedave
  • 48,414
  • 8
  • 88
  • 101
  • 18
    `if (!$capitalizeFirstCharacter) { $str = lcfirst($str); }` – AVProgrammer Jul 19 '13 at 06:51
  • 3
    Note that `ucwords` actually accepts a delimiter as second parameter (see [answer by PeterM](http://stackoverflow.com/a/33122760/2580794)), so one of the `str_replace` calls would be unnecessary. – Lars Ebert Feb 14 '17 at 12:14
  • Thanks for the info @LarsEbert. I've updated the answer. – webbiedave Feb 16 '17 at 23:08
  • The condition can be rewritten with the usage of the ternary operator ```$str = ! $capitalizeFirstCharacter ? lcfirst($str) : $str;``` mainly for readability (though some may disagree) and/or reducing code complexity. – Chris Athanasiadis May 27 '20 at 07:38
73

This can be done very simply, by using ucwords which accepts delimiter as param:

function camelize($input, $separator = '_')
{
    return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}

NOTE: Need php at least 5.4.32, 5.5.16

Mojtaba
  • 4,852
  • 5
  • 21
  • 38
PeterM
  • 1,478
  • 1
  • 22
  • 28
  • 39
    This will return something like CamelCase - if you want this to be something like camelCase then: `return str_replace($separator, '', lcfirst(ucwords($input, $separator)));` – Jeff S. Nov 16 '15 at 04:09
  • `ucwords` has a second parameter `delimiter`, so `str_replace("_", "", ucwords($input, "_"));` is good enough (in most cases, :P – Kacifer May 23 '17 at 08:42
  • 1
    For clarity: the answer of [PeterM](https://stackoverflow.com/users/5444623/peterm) will return *upper camel case* (= PascalCase). The comment of [Jeff S.](https://stackoverflow.com/users/670511/jeff-s) will return *lower camel case* (= dromedary case). – Daan May 18 '21 at 08:02
  • Either way. The OP needed a solution for kebab-case not snake_case. – theking2 Sep 19 '21 at 09:54
14

In Laravel use Str::camel()

use Illuminate\Support\Str;

$converted = Str::camel('foo_bar');

// fooBar
Ronald Araújo
  • 1,395
  • 4
  • 19
  • 30
12

Overloaded one-liner, with doc block...

/**
 * Convert underscore_strings to camelCase (medial capitals).
 *
 * @param {string} $str
 *
 * @return {string}
 */
function snakeToCamel ($str) {
  // Remove underscores, capitalize words, squash, lowercase first.
  return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}
doublejosh
  • 5,548
  • 4
  • 39
  • 45
10

this is my variation on how to deal with it. Here I have two functions, first one camelCase turns anything into a camelCase and it wont mess if variable already contains cameCase. Second uncamelCase turns camelCase into underscore (great feature when dealing with database keys).

function camelCase($str) {
    $i = array("-","_");
    $str = preg_replace('/([a-z])([A-Z])/', "\\1 \\2", $str);
    $str = preg_replace('@[^a-zA-Z0-9\-_ ]+@', '', $str);
    $str = str_replace($i, ' ', $str);
    $str = str_replace(' ', '', ucwords(strtolower($str)));
    $str = strtolower(substr($str,0,1)).substr($str,1);
    return $str;
}
function uncamelCase($str) {
    $str = preg_replace('/([a-z])([A-Z])/', "\\1_\\2", $str);
    $str = strtolower($str);
    return $str;
}

lets test both:

$camel = camelCase("James_LIKES-camelCase");
$uncamel = uncamelCase($camel);
echo $camel." ".$uncamel;
Playnox
  • 1,087
  • 14
  • 9
  • This function returns jamesLikesCameAse for camelCase instead of jamesLikesCameCase – Alari Truuts Apr 16 '19 at 12:52
  • @Alari [this demo](https://3v4l.org/9F3PB) proves your comment incorrect. Please remove your comment. – mickmackusa Dec 07 '21 at 11:13
  • @mickmackusa Not true, please try again... lol, even in your demo - it does exactly what requested (Convert string with dashes to camelCase) – Playnox Dec 09 '21 at 03:38
  • @Play You misunderstand, I am supporting your answer. I am asking Alari to remove the false claim/comment. – mickmackusa Dec 09 '21 at 03:52
  • If I am being honest, I don't find your `camelCase()` function to be elegant. There are several other answers on this page that are written more directly/concisely. There is a single native function to replace `strtolower(substr($str,0,1)).substr($str,1)`. I do not endorse the single-use variable `$i`. `[a-zA-Z0-9_]` is more simply written as `\w`. – mickmackusa Dec 09 '21 at 04:01
  • @mickmackusa Sorry, my bad... :) Well, either way (this was posted back in 2014) enjoy! – Playnox Dec 11 '21 at 14:47
6

I would probably use preg_replace_callback(), like this:

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
  return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
}

function removeDashAndCapitalize($matches) {
  return strtoupper($matches[0][1]);
}
Paige Ruten
  • 172,675
  • 36
  • 177
  • 197
5

You're looking for preg_replace_callback, you can use it like this :

$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
     return ucfirst($matches[1]);
}, $dashes);
Sparkup
  • 3,686
  • 2
  • 36
  • 50
4

here is very very easy solution in one line code

    $string='this-is-a-string' ;

   echo   str_replace('-', '', ucwords($string, "-"));

output ThisIsAString

Abbbas khan
  • 306
  • 2
  • 15
4

Try this:

$var='snake_case';
$ucword= ucword($var,'_');
echo $ucword;

Output:

Snake_Case 

remove _ with str_replace

 str_replace('_','',$ucword); //SnakeCase

and result

 $result='SnakeCase';  //pascal case
 echo lcfirst('SnakeCase');  //snakeCase (camel case)

the important thing is the approach here I used snake case and camel case in the example

dılo sürücü
  • 3,821
  • 1
  • 26
  • 28
3
$string = explode( "-", $string );
$first = true;
foreach( $string as &$v ) {
    if( $first ) {
        $first = false;
        continue;
    }
    $v = ucfirst( $v );
}
return implode( "", $string );

Untested code. Check the PHP docs for the functions im-/explode and ucfirst.

svens
  • 11,438
  • 6
  • 36
  • 55
2

One liner, PHP >= 5.3:

$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));
Tim
  • 2,805
  • 25
  • 21
2

The TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.

https://github.com/edertone/TurboCommons

To use it, import the phar file to your project and:

use org\turbocommons\src\main\php\utils\StringUtils;

echo StringUtils::formatCase('sNake_Case', StringUtils::FORMAT_CAMEL_CASE);

// will output 'sNakeCase'

Here's the link to the method source code:

https://github.com/edertone/TurboCommons/blob/b2e015cf89c8dbe372a5f5515e7d9763f45eba76/TurboCommons-Php/src/main/php/utils/StringUtils.php#L653

Jaume Mussons Abad
  • 706
  • 1
  • 6
  • 20
2

Try this ;)

$string = 'this-is-a-string';
$separator = '-';

$stringCamelize = str_replace(
    $separator,
    '',
    lcfirst(
        ucwords(
            strtolower($string),
            $separator
        )
    )
);

var_dump($stringCamelize); // -> 'thisIsAString'
Gigoland
  • 1,287
  • 13
  • 10
  • What new value does this unexplained answer bring versus the many earlier posted techniques that make the same function calls? – mickmackusa Apr 18 '23 at 07:10
1

Alternatively, if you prefer not to deal with regex, and want to avoid explicit loops:

// $key = 'some-text', after transformation someText            
$key = lcfirst(implode('', array_map(function ($key) {
    return ucfirst($key);
}, explode('-', $key))));
Victor Farazdagi
  • 3,080
  • 2
  • 21
  • 30
1
function camelize($input, $separator = '_')
{
    return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}

echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
  • Incomplete and incorrect code. Please test before posting. – theking2 Sep 19 '21 at 09:52
  • I agree this is not a working demonstration. It will confuse researchers. Plus this general technique existed earlier on this page. I don't find this answer to add any new value to this page. – mickmackusa Dec 07 '21 at 11:46
1

Many good solutions above, and I can provide a different way that no one mention before. This example uses array. I use this method on my project Shieldon Firewall.

/**
 * Covert string with dashes into camel-case string.
 *
 * @param string $string A string with dashes.
 *
 * @return string
 */
function getCamelCase(string $string = '')
{
    $str = explode('-', $string);
    $str = implode('', array_map(function($word) {
        return ucwords($word); 
    }, $str));

    return $str;
}

Test it:

echo getCamelCase('This-is-example');

Result:

ThisIsExample
Terry Lin
  • 2,529
  • 22
  • 21
  • Almost. Stictly speaking that is PascalCase not camelCase. But we leave the correct solution as an excersise.... – theking2 Sep 19 '21 at 09:47
1

Some very good solutions here. I compiled them together for easy c&p

declare(strict_types=1);
/**
 * convert kebab-case to PascalCase
 */
function kebabToPascal( string $str ): string {
   return str_replace( ' ', '', ucwords( str_replace( '-', ' ', $str ) ) );
}

/**
 * convert snake_case to PascalCase
 */
function snakeToPascal( string $str ): string {
  return str_replace (' ', '', ucwords( str_replace( '_', ' ', $str ) ) );
}

/**
  * convert snake_case to camelCase
  */
 function snakeToCamel( string $str ): string {
  return lcfirst( snakeToPascal( $str ) );
}

/**
 * convert kebab-case to camelCase
 */
function kebabToCamel( string $str): string {
  return lcfirst( kebabToPascal( $str ) );
}



echo snakeToCamel( 'snake_case' ). '<br>';
echo kebabToCamel( 'kebab-case' ). '<br>';
echo snakeToPascal( 'snake_case' ). '<br>';
echo kebabToPascal( 'kebab-case' ). '<br>';

echo kebabToPascal( 'It will BREAK on things-like_this' ). '<br>';
theking2
  • 2,174
  • 1
  • 27
  • 36
1

In Yii2 you can use yii\helpers\Inflector::camelize():

use yii\helpers\Inflector;

echo Inflector::camelize("send_email");

// outputs: SendEmail

Yii provides a lot of similar functions, see the Yii2 Docs.

WeSee
  • 3,158
  • 2
  • 30
  • 58
0
function camelCase($text) {
    return array_reduce(
         explode('-', strtolower($text)),
         function ($carry, $value) {
             $carry .= ucfirst($value);
             return $carry;
         },
         '');
}

Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...

  • 1
    I don't really see how this is simpler, clearer or anyhow better than the solution provided (and accepted) about 4 years ago. – ccjmne Aug 29 '14 at 00:12
0

Another simple approach:

$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));
Mr Sorbose
  • 777
  • 4
  • 20
  • 34
0

If you use Laravel framework, you can use just camel_case() method.

camel_case('this-is-a-string') // 'thisIsAString'
Marek Skiba
  • 2,124
  • 1
  • 28
  • 31
0

Here is another option:

private function camelcase($input, $separator = '-')     
{
    $array = explode($separator, $input);

    $parts = array_map('ucwords', $array);

    return implode('', $parts);
}
0

$stringWithDash = 'Pending-Seller-Confirmation'; $camelize = str_replace('-', '', ucwords($stringWithDash, '-')); echo $camelize; output: PendingSellerConfirmation

ucwords second(optional) parameter helps in identify a separator to camelize the string. str_replace is used to finalize the output by removing the separator.

R T
  • 4,369
  • 3
  • 38
  • 49
0

Here is a small helper function using a functional array_reduce approach. Requires at least PHP 7.0

private function toCamelCase(string $stringToTransform, string $delimiter = '_'): string
{
    return array_reduce(
        explode($delimiter, $stringToTransform),
        function ($carry, string $part): string {
            return $carry === null ? $part: $carry . ucfirst($part);
        }
    );
}
cb0
  • 8,415
  • 9
  • 52
  • 80
0
private function dashesToCamelCase($string)
{
    $explode = explode('-', $string);
    $return = '';
    foreach ($explode as $item) $return .= ucfirst($item);

    return lcfirst($return);
}
Čamo
  • 3,863
  • 13
  • 62
  • 114
0

This works for me:

function camelCase($string){
    $chunks = preg_split("/\s+|-|_/",$string);

    $camel = "";
        
    foreach ($chunks as $idx => $chunk){
         
        if ($idx===0){
            $camel = strtolower($chunk);
        }else{
                $camel .= ucfirst($chunk);
        }
    }
    return $camel;
}
0

The shortest and most elegant solution would be:

function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
    $result = join("", array_map("ucfirst", explode("-", $string)));

    if ($capitalizeFirstCharacter === false) {
        return lcfirst($result);
    }

    return $result;
}
Champignon
  • 37
  • 4
0

One Line Option

echo str_replace(' ', '', lcfirst(ucwords(str_replace("_", " ", 'facebook_catalog_id_type')))); 
//output: facebookCatalogIdType
Murat Çakmak
  • 151
  • 2
  • 7
-1

Try this:

 return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
Jakub Hampl
  • 39,863
  • 10
  • 77
  • 106
-2

This is simpler :

$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );