Convert Dashes to CamelCase in PHP

2020-02-16 07:59发布

Can someone help me complete this PHP function? 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;
}

标签: php string
23条回答
Explosion°爆炸
2楼-- · 2020-02-16 08:56

Try this:

 return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
查看更多
▲ chillily
3楼-- · 2020-02-16 08:57

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

查看更多
可以哭但决不认输i
4楼-- · 2020-02-16 08:57

This function is similar to @Svens's function

function toCamelCase($str, $first_letter = false) {
    $arr = explode('-', $str);
    foreach ($arr as $key => $value) {
        $cond = $key > 0 || $first_letter;
        $arr[$key] = $cond ? ucfirst($value) : $value;
    }
    return implode('', $arr);
}

But clearer, (i think :D) and with the optional parameter to capitalize the first letter or not.

Usage:

$dashes = 'function-test-camel-case';
$ex1 = toCamelCase($dashes);
$ex2 = toCamelCase($dashes, true);

var_dump($ex1);
//string(21) "functionTestCamelCase"
var_dump($ex2);
//string(21) "FunctionTestCamelCase"
查看更多
放荡不羁爱自由
5楼-- · 2020-02-16 08:58

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);
        }
    );
}
查看更多
SAY GOODBYE
6楼-- · 2020-02-16 08:59

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]);
}
查看更多
登录 后发表回答