Skip to content

Instantly share code, notes, and snippets.

@carousel
Last active May 27, 2024 10:56
Show Gist options
  • Save carousel/1aacbea013d230768b3dec1a14ce5751 to your computer and use it in GitHub Desktop.
Save carousel/1aacbea013d230768b3dec1a14ce5751 to your computer and use it in GitHub Desktop.
Convert snake to camel case and back with PHP
<?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";
@RobertV17
Copy link

Thank you!

@Alex-M0
Copy link

Alex-M0 commented May 16, 2022

Mini optimization for snakeToCamel
lcfirst(str_replace('', '', ucwords($input, '')));

@jonathan1055
Copy link

Thank you @carousel this is exactly what I was looking for. Can I use it in an open source project?

@Alex-M0 your optimisation does not look right. I know there is probably a space in your first ' ' but you do not do anything with _ so it does not work.

@dhaeckel
Copy link

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