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条回答
我只想做你的唯一
2楼-- · 2020-02-16 08:36
function camelize($input, $separator = '_')
{
    return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}

echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
查看更多
女痞
3楼-- · 2020-02-16 08:37

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

$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
     return ucfirst($matches[1]);
}, $dashes);
查看更多
该账号已被封号
4楼-- · 2020-02-16 08:43

here is very very easy solution in one line code

    $string='this-is-a-string' ;

   echo   str_replace('-', '', ucwords($string, "-"));

output ThisIsAString

查看更多
Melony?
5楼-- · 2020-02-16 08:43

This is simpler :

$string = preg_replace( '/-(.?)/e',"strtoupper('$1')", strtolower( $string ) );
查看更多
Ridiculous、
6楼-- · 2020-02-16 08:45

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;
查看更多
Bombasti
7楼-- · 2020-02-16 08:46
function camelCase($text) {
    return array_reduce(
         explode('-', strtolower($text)),
         function ($carry, $value) {
             $carry .= ucfirst($value);
             return $carry;
         },
         '');
}

Obviously, if another delimiter than '-', e.g. '_', is to be matched too, then this won't work, then a preg_replace could convert all (consecutive) delimiters to '-' in $text first...

查看更多
登录 后发表回答