Convert Dashes to CamelCase in PHP

前端 未结 25 1195
南笙
南笙 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

    here is very very easy solution in one line code

        $string='this-is-a-string' ;
    
       echo   str_replace('-', '', ucwords($string, "-"));
    

    output ThisIsAString

    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2020-12-07 20:28

    Another simple approach:

    $nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
    $cameled = lcfirst(str_replace($nasty, '', ucwords($string)));
    
    0 讨论(0)
  • 2020-12-07 20:28

    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
    
    0 讨论(0)
  • 2020-12-07 20:29

    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

    0 讨论(0)
  • 2020-12-07 20:29
    $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.

    0 讨论(0)
提交回复
热议问题