# 找出字符串中的大写字母替换为“\_” + “小写字母”

**URL:** <https://www.shiqidu.com/t/topic/339>\
**Category:** 开发调优\
**Tags:** PHP\
**Created:** [2017 年12 月 11 日 04:35 UTC](https://www.shiqidu.com/t/topic/339 "2017-12-11T04:35:04Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

作者： ![Leon](https://www.shiqidu.com/user_avatar/www.shiqidu.com/leon/32/5_2.png) [@Leon](https://www.shiqidu.com/u/Leon)\
发布日期： [2017 年12 月 11 日 04:35 UTC](https://www.shiqidu.com/t/topic/339/1 "2017-12-11T04:35:04Z")

</div>

其实使用正则也可以很容易的实现，但是感觉性能会低些（其实字符串很短的话并没有什么影响）。

```php
/**  
 * 驼峰转`_`+`小写`  
 * @example `msgId` => `msg_id`  
 * @param string $word  
 * @return string  
 */  
function camelCase2underScoreCase($word = '')  
{  
    $uc_word = '';  
    if (!empty($word)) {  
        $word_arr = str_split($word);  
        if (!empty($word_arr)) {  
            foreach ($word_arr as $k) {  
                if (ord($k) >= 65 && ord($k) <= 90) {  
                    $k = '_' . chr(ord($k) + 32);  
                }  
                $uc_word .= $k;  
            }  
        }  
    }  
    return $uc_word;  
}  

```

### 使用方法

```php
$result = camelCase2underScoreCase('msgId');  
var_dump($result);  
// 输出 'msg_id'  

```

### 应用场景

主要是最近工作中使用到了网易云信的消息抄送功能，这厮返回的数据都是这样的

```auto
{"fromNick":"saonian","msgType":"TEXT","msgidServer":"8965196916","fromAccount":"16","fromClientType":"WEB","fromDeviceId":"14f2f3f0b3e1e70765dd15f87b708174","eventType":"1","body":"hello world","convType":"PERSON","msgidClient":"3d7192175e8bbe541e93dc1e4bda2c10","resendFlag":"0","msgTimestamp":"1512961795251","to":"98"}  

```

`json_decode`转为数组后，要存到数据库不好处理(数据库字段名为\_命名)，所以写了这个函数。希望对大家有帮助。
