码迷,mamicode.com
首页 > 其他好文 > 详细

将下划线格式的字符串转换为骆峰格式的字符串

时间:2015-08-28 08:27:53      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:

一、方法一:

 1 <?php
 2 /**
 3  * 将下划线风格的名称转换为骆峰格式
 4  * @param string $string 骆峰格式字符串
 5  * @param boolean $firstLetter 是否将第一个字符也转换成大写,默认为小写
 6  * @return string
 7  */
 8 function toCamelCase($string, $firstLetter = false) {
 9     $arr = explode(‘_‘, $string);
10     foreach ($arr as $key => $value) {
11         $flag = $key > 0 || $firstLetter;
12         $arr[$key] = $flag ? ucfirst($value) : $value;
13     }
14     return implode(‘‘, $arr);
15 }
16 $arr = [
17     toCamelCase(‘to_camel_case‘),
18     toCamelCase(‘simple_2‘),
19     toCamelCase(‘simple_XML‘),
20     toCamelCase(‘PDFLoad‘),
21     toCamelCase(‘AStringToArray‘),
22     toCamelCase(‘test123_some_string‘),
23     toCamelCase(‘start_middle_end_eof‘),
24     toCamelCase(‘abc_def_123_deny_success‘, true),
25 ];
26 print_r($arr);
27 
28 运行结果:
29 Array
30 (
31     [0] => toCamelCase
32     [1] => simple2
33     [2] => simpleXML
34     [3] => PDFLoad
35     [4] => AStringToArray
36     [5] => test123SomeString
37     [6] => startMiddleEndEof
38     [7] => AbcDef123DenySuccess
39 )

二、方法二:

 1 <?php
 2 /**
 3  * 将下划线风格的名称转换为骆峰格式
 4  * @param string $string 骆峰格式字符串
 5  * @param boolean $firstLetter 是否将第一个字符也转换成大写,默认为小写
 6  * @return string
 7  */
 8 function toCamelCase($string, $isFirstLetter = false) {
 9     $string = str_replace(‘ ‘, ‘‘, ucwords(str_replace(‘_‘, ‘ ‘, $string)));
10     if ($isFirstLetter) {
11         return $string;
12     }
13     return lcfirst($string);
14 
15 }
16 $arr = [
17     toCamelCase(‘to_camel_case‘),
18     toCamelCase(‘simple_2‘),
19     toCamelCase(‘simple_XML‘),
20     toCamelCase(‘PDFLoad‘),
21     toCamelCase(‘AStringToArray‘),
22     toCamelCase(‘test123_some_string‘),
23     toCamelCase(‘start_middle_end_eof‘),
24     toCamelCase(‘abc_def_123_deny_success‘, true),
25 ];
26 print_r($arr);
27 
28 运行结果:
29 Array
30 (
31     [0] => toCamelCase
32     [1] => simple2
33     [2] => simpleXML
34     [3] => pDFLoad
35     [4] => aStringToArray
36     [5] => test123SomeString
37     [6] => startMiddleEndEof
38     [7] => AbcDef123DenySuccess
39 )

三、方法三:

将下划线格式的字符串转换为骆峰格式的字符串

标签:

原文地址:http://www.cnblogs.com/atblog/p/4765409.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!