Convert Dashes to CamelCase in PHP

前端 未结 25 1194
南笙
南笙 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:29

    Try this:

     return preg_replace("/\-(.)/e", "strtoupper('\\1')", $string);
    
    0 讨论(0)
  • 2020-12-07 20:30

    You're looking for preg_replace_callback, you can use it like this :

    $camelCase = preg_replace_callback('/-(.?)/', function($matches) {
         return ucfirst($matches[1]);
    }, $dashes);
    
    0 讨论(0)
  • 2020-12-07 20:30
    function camelize($input, $separator = '_')
    {
        return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
    }
    
    echo ($this->camelize('someWeir-d-string'));
    // output: 'someWeirdString';
    
    0 讨论(0)
  • 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;
    
    0 讨论(0)
  • 2020-12-07 20:32
    private function dashesToCamelCase($string)
    {
        $explode = explode('-', $string);
        $return = '';
        foreach ($explode as $item) $return .= ucfirst($item);
    
        return lcfirst($return);
    }
    
    0 讨论(0)
  • 2020-12-07 20:33

    Here is another option:

    private function camelcase($input, $separator = '-')     
    {
        $array = explode($separator, $input);
    
        $parts = array_map('ucwords', $array);
    
        return implode('', $parts);
    }
    
    0 讨论(0)
提交回复
热议问题