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";
@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