问题描述
有人可以帮助我完成此PHP函数吗?我想要一个这样的字符串:'this-is-a-string'并将其转换为:'thisIsAString':
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;
}
推荐答案
无需正则表达式或回调. ucword几乎可以完成所有工作:
No regex or callbacks necessary. Almost all the work can be done with 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');
如果您使用的是PHP> = 5.3,则可以使用lcfirst代替strtolower.
If you're using PHP >= 5.3, you can use lcfirst instead of strtolower.
PHP 5.4.32/5.5.16中的ucword中添加了第二个参数,这意味着我们不需要首先将破折号更改为空格(感谢Lars Ebert和PeterM指出了这一点).这是更新的代码:
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:
function dashesToCamelCase($string, $capitalizeFirstCharacter = false)
{
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
}
echo dashesToCamelCase('this-is-a-string');
这篇关于在PHP中将Dashs转换为CamelCase的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!