Last active
April 14, 2025 14:58
-
-
Save carousel/1aacbea013d230768b3dec1a14ce5751 to your computer and use it in GitHub Desktop.
Convert snake to camel case and back with PHP
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 camel_to_snake($input) | |
{ | |
return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $input)); | |
} | |
function snakeToCamel($input) | |
{ | |
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $input)))); | |
} | |
$camel = 'CreateUserProfile'; | |
$snake = camel_to_snake($camel); | |
echo 'to_snake: ' . $snake . "\n"; | |
$camel = snakeToCamel($snake); | |
echo 'toCamel: ' . $camel . "\n"; |
Mini optimization for snakeToCamel
lcfirst(str_replace('', '', ucwords($input, '')));
Thanks for the Gist. I actually came up with another version for snakeToCamel, skipping one str_replace call
<?php
function snakeToCamelCase(string $input): string
{
return \lcfirst(\str_replace('_', '', \ucwords($input, '_')));
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you!