【发布时间】:2020-02-01 07:08:56
【问题描述】:
我有以下内容
"aa_bb" : "foo"
"pp_Qq" : "bar"
"Xx_yY_zz" : "foobar"
我想把左边的内容转换成camelCase
"aaBb" : "foo"
"ppQq" : "bar"
"xxYyZz" : "foobar"
还有代码:
// selects the left part
$newString = preg_replace_callback("/\"(.*?)\"(.*?):/", function($matches) {
// selects the characters following underscores
$matches[1] = preg_replace_callback("/_(.?)/", function($matches) {
//removes the underscore and uppercases the character
return strtoupper($matches[1]);
}, $matches[1]);
// lowercases the first character before returning
return "\"".lcfirst($matches[1])."\" : ".$matches[2];
}, $string);
这段代码可以简化吗?
注意:内容将始终为单个字符串。
【问题讨论】:
-
您可以稍微简化一下您的正则表达式,即
^"([^"]+)"\s*: -
@CodeManiac 我会试试看。
-
@user3783243 空格可能不一致。
-
@user3783243 引号之外的任何地方。引号之间肯定没有空格。
-
@user3783243 抱歉,误读了您的代码。此外,内容将不能作为数组使用。早该澄清的。内容将以字符串形式提供。
标签: php regex pcre preg-replace-callback camelcasing