我有一个具有以下内容的文件
“ aa_bb”:“ foo”
“ pp_Qq”:“栏”
“ Xx_yY”:“ foobar”
而且我想将左侧的内容转换为camelCase
“ aaBb”:“ foo”
“ ppQq”:“栏”
“ xxYY”:“ foobar”
和代码:
// selects the left part
$newfileContents = 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];
}, $fileContents);
此代码可以简化吗?
<?php
$fileContents = '
"aa_bb" : "foo"
"pp_Qq" : "bar"
"Xx_yY" : "foobar"
';
echo "<pre>\n" . $fileContents . \n</pre>";
$newfileContents = preg_replace_callback('/"(.*)"( *):/', function($matches) {
// selects the characters between speechmarks
$matches[1] = preg_replace_callback("/_(.?)/", function($matches) {
//removes the underscore and uppercasing the first character
return strtoupper($matches[1]);
}, $matches[1]);
// lowercasing the first character
return '"' . lcfirst($matches[1]) . '" :' . trim($matches[2]);
}, $fileContents);
echo "<pre>\n" . $newfileContents . "\n</pre>";
?>
"aa_bb" : "foo"
"pp_Qq" : "bar"
"Xx_yY" : "foobar"
"aaBb" : "foo"
"ppQq" : "bar"
"xxYY" : "foobar"