在 PHP 中将破折号转换为 CamelCase
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/2791998/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert Dashes to CamelCase in PHP
提问by Kirk Ouimet
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':
有人可以帮我完成这个 PHP 功能吗?我想取这样的字符串:'this-is-a-string' 并将其转换为:'thisIsAString':
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
    // Do stuff
    return $string;
}
回答by webbiedave
No regex or callbacks necessary. Almost all the work can be done with ucwords:
不需要正则表达式或回调。几乎所有的工作都可以用ucwords完成:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) 
{
    $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
    if (!$capitalizeFirstCharacter) {
        $str[0] = strtolower($str[0]);
    }
    return $str;
}
echo dashesToCamelCase('this-is-a-string');
If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.
如果您使用的是 PHP >= 5.3,则可以使用 lcfirst 而不是 strtolower。
Update
更新
A second parameter was added to ucwords in PHP 5.4.32/5.5.16 which means we don't need to first change the dashes to spaces (thanks to Lars Ebert and PeterM for pointing this out). Here is the updated code:
在 PHP 5.4.32/5.5.16 中向 ucwords 添加了第二个参数,这意味着我们不需要先将破折号更改为空格(感谢 Lars Ebert 和 PeterM 指出这一点)。这是更新后的代码:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) 
{
    $str = str_replace('-', '', ucwords($string, '-'));
    if (!$capitalizeFirstCharacter) {
        $str = lcfirst($str);
    }
    return $str;
}
echo dashesToCamelCase('this-is-a-string');
回答by PeterM
回答by Playnox
this is my variation on how to deal with it. Here I have two functions, first one camelCaseturns anything into a camelCase and it wont mess if variable already contains cameCase. Second uncamelCaseturns camelCase into underscore (great feature when dealing with database keys).
这是我如何处理它的变化。这里我有两个函数,第一个camelCase将任何东西转换为camelCase,如果变量已经包含camelCase,它就不会乱七八糟。第二个uncamelCase将 camelCase 转换为下划线(处理数据库键时的强大功能)。
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;
回答by doublejosh
Overloaded one-liner, with doc block...
超载单行,带有文档块...
/**
 * Convert underscore_strings to camelCase (medial capitals).
 *
 * @param {string} $str
 *
 * @return {string}
 */
function snakeToCamel ($str) {
  // Remove underscores, capitalize words, squash, lowercase first.
  return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}
回答by Jeremy Ruten
I would probably use preg_replace_callback(), like this:
我可能会使用preg_replace_callback(),像这样:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false) {
  return preg_replace_callback("/-[a-zA-Z]/", 'removeDashAndCapitalize', $string);
}
function removeDashAndCapitalize($matches) {
  return strtoupper($matches[0][1]);
}
回答by Sparkup
You're looking for preg_replace_callback, you can use it like this :
您正在寻找preg_replace_callback,您可以像这样使用它:
$camelCase = preg_replace_callback('/-(.?)/', function($matches) {
     return ucfirst($matches[1]);
}, $dashes);
回答by B?a?ej Krzakala
function camelize($input, $separator = '_')
{
    return lcfirst(str_replace($separator, '', ucwords($input, $separator)));
}
echo ($this->camelize('someWeir-d-string'));
// output: 'someWeirdString';
回答by svens
$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.
未经测试的代码。检查 PHP 文档中的 im-/explode 和 ucfirst 函数。
回答by Tim
One liner, PHP >= 5.3:
一个班轮,PHP >= 5.3:
$camelCase = lcfirst(join(array_map('ucfirst', explode('-', $url))));
回答by Mr Sorbose
Another simple approach:
另一种简单的方法:
$nasty = [' ', '-', '"', "'"]; // array of nasty characted to be removed
$cameled = lcfirst(str_replace($nasty, '', ucwords($string)));

