Convert Dashes to CamelCase in PHP

前端 未结 25 1337
南笙
南笙 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条回答
  •  旧时难觅i
    2020-12-07 20:32

    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;
    

提交回复
热议问题