Occasionally encountered this problem, feel some meaning, and then studied a bit.
Underline to the hump is relatively simple, directly according to the underline to break up the group, each child first character to capitalize, and then do string stitching.
The hump turns to underline style, slightly more complicated. At first I had no idea, and then I thought, you can traverse the string, encounter uppercase letters, convert it to lowercase, and add an underscore in front.
Final implementation:
Class cameltool{//Hump naming method to underline style public static function Tounderscore ($STR) {$array = array (), for ($i =0; $i <strlen ($STR); $i + +) {if ($str [$i] = = Strtolower ($str [$i]) {$array [] = $str [$i];} Else{if ($i >0) {$array [] = ' _ ';} $array [] = Strtolower ($str [$i]);}} $result = Implode ("', $array); return $result;} Underline style Goto Hump naming method public static function Tocamelcase ($STR) {$array = explode (' _ ', $str); $result = "; foreach ($array as $ Value) {$result. = Ucfirst ($value);} return $result;}}
There is not much to traverse the string, but PHP provides this powerful feature:
for ($i =0; $i < strlen ($STR); $i + +) { echo $str [$i];}
We can manipulate each character of a string as if it were traversing an array.
How do I detect a letter that is capitalized? At first I was ready to use regular expressions, but soon I thought of a simpler way:
$str! = Strtolower ($STR);
If this condition is true, $STR must be capital letters.
Test that the code is running correctly:
$str = ' User_point_log '; $result = Cameltool::tocamelcase ($STR);//output Userpointlogecho $result; Echo ' <br/> '; $str ' Userpointlog '; $result = Cameltool::tounderscore ($STR);//output User_point_logecho $result;
Hump naming and underline style cross-transfer