Last active
March 29, 2025 00:56
-
-
Save robocoder/789e37c993d96417997d160e78aae697 to your computer and use it in GitHub Desktop.
Converting to PascalCase, camelCase, kebab-case, snake_case, and SCREAMING_SNAKE_CASE
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 | |
/** | |
* @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)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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
_
.