Hump naming and underline style cross-transfer

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.