PHP下划线和驼峰字符串相互转换

PHP下划线和驼峰字符串相互转换

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
class AppBlogString
{
/*
* 下划线转驼峰
*/
public static function convertUnderline($str)
{
$str = preg_replace_callback('/([-_]+([a-z]{1}))/i', function ($matches) {
return strtoupper($matches[2]);
}, $str);
return $str;
}

/*
* 驼峰转下划线
*/
public static function humpToLine($str)
{
$str = preg_replace_callback('/([A-Z]{1})/', function ($matches) use ($str) {
if ($matches[0] != substr($str, 0, 1))
return '_' . strtolower($matches[0]);
else
return strtolower($matches[0]);
}, $str);
return $str;
}

public static function convertHump(array $data)
{
$result = [];
foreach ($data as $key => $item) {
if (is_array($item) || is_object($item)) {
$result[$this->humpToLine($key)] = $this->convertHump((array) $item);
} else {
$result[$this->humpToLine($key)] = $item;
}
}
return $result;
}
}

Powered by AppBlog.CN     浙ICP备14037229号

Copyright © 2012 - 2020 APP开发技术博客 All Rights Reserved.

访客数 : | 访问量 :