Convert Dashes to CamelCase in PHP

前端 未结 25 1299
南笙
南笙 2020-12-07 19:40

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 d         


        
25条回答
  •  死守一世寂寞
    2020-12-07 20:27

    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"
    

提交回复
热议问题