正则表达式:
(?<=")[a-z_]+(?=":)
匹配示例:
{"api_token":"1,32|xxx","identity_token":"1,1598333646,xxx,2","user":{"nickname":"scsasdad","avatar":"111111","country_code":null,"telephone":"xxx","email":"","language":"zh","last_login_time":xxx,"status":20,"user_id":1,"user_profile":{"user_id":1,"first_name":"阳","last_name":"","gender":1,"birthday":"1990-09-19","company":"xx科技","industry":"计算机","position":"后端工程师","education":"本科","address":"xx花园","city":"武汉","postcode":"430000","country":"中国"}}}
我做这个的用途是,有时候不同的接口需要的返回格式不一致,有的需要返回snake键名,有时候需要camlCase键名。具体代码如下:
/**
* 蛇形转camel
* @author Bruce 2020-08-25
*
* @param string $value [description]
* @return [type] [description]
*/
function snake_to_camel($value = '')
{
$value = ucwords(str_replace(['-', '_'], ' ', $value));
return lcfirst(str_replace(' ', '', $value));
}
/**
* 多维数组的key变成camelCase
* @author Bruce 2020-08-25
*
* @param array $result [description]
* @return [type] [description]
*/
function camel_result($result = [])
{
$result = json_encode($result, 320);
$new = preg_replace_callback('/(?<=")[a-z_]+(?=":)/', function ($matches) {
return snake_to_camel($matches[0]);
}, $result);
return json_decode($new, true);
}
多维结果示例: