Created
July 17, 2021 21:30
-
-
Save azerum/8851cea41715a76fd3f8c8049066dbf1 to your computer and use it in GitHub Desktop.
Convert snake_case to camelCase in PHP and vice versa
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| function snake_to_camel_case(string $string): string { | |
| $parts = explode('_', $string); | |
| $parts_count = count($parts); | |
| for ($i = 1; $i < $parts_count; ++$i) { | |
| $parts[$i] = ucfirst($parts[$i]); | |
| } | |
| return implode('', $parts); | |
| } | |
| function camel_to_snake_case(string $string): string { | |
| $s = preg_replace('/([a-z0-9])([A-Z])/', '$1_$2', $string); | |
| $s = preg_replace('/([A-Z])([A-Z])([a-z])/', '$1_$2$3', $s); | |
| return strtolower($s); | |
| } | |
| $tests = array( | |
| 'simpleTest' => 'simple_test', | |
| 'easy' => 'easy', | |
| 'HTML' => 'html', | |
| 'simpleXML' => 'simple_xml', | |
| 'PDFLoad' => 'pdf_load', | |
| 'startMIDDLELast' => 'start_middle_last', | |
| 'AString' => 'a_string', | |
| 'Some4Numbers234' => 'some4_numbers234', | |
| 'TEST123String' => 'test123_string', | |
| ); | |
| foreach ($tests as $test => $expected) { | |
| $result = camel_to_snake_case($test); | |
| if ($result === $expected) { | |
| echo "Pass: $test => $expected"; | |
| } else { | |
| echo "Fail: $test => $expected [$result]"; | |
| } | |
| echo '<br>'; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment