Skip to content

Instantly share code, notes, and snippets.

@robocoder
Last active March 29, 2025 00:56
Show Gist options
  • Save robocoder/789e37c993d96417997d160e78aae697 to your computer and use it in GitHub Desktop.
Save robocoder/789e37c993d96417997d160e78aae697 to your computer and use it in GitHub Desktop.
Converting to PascalCase, camelCase, kebab-case, snake_case, and SCREAMING_SNAKE_CASE
<?php
/**
* @license CC0
* @copyright 2025 Anthon Pang
* @author Anthon Pang <[email protected]>
*/
/**
* Case Converter
*/
class CaseConverter
{
/**
* Translate "case"
*
* @param string $targetCase one of 'pascal', 'camel', 'kebab', 'snake', 'screaming snake'
* @param string $symbol
*
* @return string
*/
public function translate($targetCase, $symbol)
{
if (strpos($symbol, '-') !== false || strpos($symbol, '_') !== false) {
// kebab or snake
$words = preg_split('~[_-]+~', $symbol);
} elseif (! preg_match('~[a-z]~', $symbol)) {
// screaming
$words = [$symbol];
} else {
// pascal or camel
preg_match_all('~(^[a-z][^A-Z]*|[A-Z]+[^A-Z]*)~', $symbol, $matches);
$words = $matches[0];
}
switch ($targetCase) {
case 'pascal':
return implode('', array_map('ucfirst', $words));
case 'camel':
return lcfirst(implode('', $words));
case 'kebab':
return implode('-', array_map('strtolower', $words));
case 'snake':
return implode('_', array_map('strtolower', $words));
default:
return implode('_', array_map('strtoupper', $words));
}
}
}
@robocoder
Copy link
Author

Don't send pull requests. I was bored one night and just coded this for fun.

There are unhandled cases, e.g., where the symbol is _.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment