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条回答
Juvenile、少年°
2楼-- · 2020-02-16 08:47

Another simple approach:

$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));
查看更多
劫难
3楼-- · 2020-02-16 08:47

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

camel_case('this-is-a-string') // 'thisIsAString'
查看更多
Summer. ? 凉城
4楼-- · 2020-02-16 08:48
$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.

查看更多
Summer. ? 凉城
5楼-- · 2020-02-16 08:49

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))));
查看更多
男人必须洒脱
6楼-- · 2020-02-16 08:49

In Laravel use Str::camel()

use Illuminate\Support\Str;

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

// fooBar
查看更多
混吃等死
7楼-- · 2020-02-16 08:50

One liner, PHP >= 5.3:

$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));
查看更多
登录 后发表回答