Convert string with dashes to camelCase

PhpString

Php Problem Overview


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

Php Solutions


Solution 1 - Php

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');

Solution 2 - Php

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

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

NOTE: Need php at least 5.4.32, 5.5.16

Solution 3 - Php

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))));
}

Solution 4 - Php

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;

Solution 5 - Php

In Laravel use Str::camel()

use Illuminate\Support\Str;

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

// fooBar

Solution 6 - Php

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]);
}

Solution 7 - Php

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

$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
     return ucfirst($matches[1]);
}, $dashes);

Solution 8 - Php

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

Solution 9 - Php

here is very very easy solution in one line code

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

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

output ThisIsAString

Solution 10 - Php

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

echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';

Solution 11 - Php

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

Solution 12 - Php

One liner, PHP >= 5.3:

$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));

Solution 13 - Php

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

Solution 14 - Php

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))));

Solution 15 - Php

Another simple approach:

$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));

Solution 16 - Php

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

Solution 17 - Php

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

Solution 18 - Php

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

Solution 19 - Php

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

camel_case('this-is-a-string') // 'thisIsAString'

Solution 20 - Php

Here is another option:

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

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

    return implode('', $parts);
}

Solution 21 - Php

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

Solution 22 - Php

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);
        }
    );
}

Solution 23 - Php

private function dashesToCamelCase($string)
{
	$explode = explode('-', $string);
	$return = '';
	foreach ($explode as $item) $return .= ucfirst($item);

	return lcfirst($return);
}

Solution 24 - Php

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.

Solution 25 - Php

Try this ;)

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

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

var_dump($stringCamelize); // -> 'thisIsAString'

Solution 26 - Php

Try this:

 return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);

Solution 27 - Php

This is simpler :

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKirk OuimetView Question on Stackoverflow
Solution 1 - PhpwebbiedaveView Answer on Stackoverflow
Solution 2 - PhpPeterMView Answer on Stackoverflow
Solution 3 - PhpdoublejoshView Answer on Stackoverflow
Solution 4 - PhpPlaynoxView Answer on Stackoverflow
Solution 5 - PhpRonald AraújoView Answer on Stackoverflow
Solution 6 - PhpPaige RutenView Answer on Stackoverflow
Solution 7 - PhpSparkupView Answer on Stackoverflow
Solution 8 - PhpsvensView Answer on Stackoverflow
Solution 9 - PhpAbbbas khanView Answer on Stackoverflow
Solution 10 - PhpBłażej KrzakalaView Answer on Stackoverflow
Solution 11 - Phpdılo sürücüView Answer on Stackoverflow
Solution 12 - PhpTimView Answer on Stackoverflow
Solution 13 - PhpJaume Mussons AbadView Answer on Stackoverflow
Solution 14 - PhpVictor FarazdagiView Answer on Stackoverflow
Solution 15 - PhpMr SorboseView Answer on Stackoverflow
Solution 16 - PhpTerry LinView Answer on Stackoverflow
Solution 17 - Phptheking2View Answer on Stackoverflow
Solution 18 - PhpPeerGumView Answer on Stackoverflow
Solution 19 - PhpMarek SkibaView Answer on Stackoverflow
Solution 20 - PhpMariano EcheverríaView Answer on Stackoverflow
Solution 21 - PhpR TView Answer on Stackoverflow
Solution 22 - Phpcb0View Answer on Stackoverflow
Solution 23 - PhpČamoView Answer on Stackoverflow
Solution 24 - PhpWeSeeView Answer on Stackoverflow
Solution 25 - PhpGigolNftView Answer on Stackoverflow
Solution 26 - PhpJakub HamplView Answer on Stackoverflow
Solution 27 - PhpsnwalkundeView Answer on Stackoverflow