Skip to content

Instantly share code, notes, and snippets.

@wojtha
Last active September 4, 2020 08:51
Show Gist options
  • Save wojtha/11035496 to your computer and use it in GitHub Desktop.
Save wojtha/11035496 to your computer and use it in GitHub Desktop.
CaseConverter an static class for conversions betweenn camelCase <--> StudlyCase <--> snake_case.
<?php
/**
* Class CaseConverter
*
* Library for camelCase/StudlyCase/snake_case conversions.
*/
class CaseConverter {
/**
* snake_case to camelCase
*
* @param string $str
* @return string
*/
static function snakeToCamel($str) {
return lcfirst(str_replace(' ', '', ucwords(str_replace('_', ' ', $str))));
}
/**
* snake_case to StudlyCaps
*
* @param string $str
* @return string
*/
static function snakeToStudly($str) {
return str_replace(' ', '', ucwords(str_replace('_', ' ', $str)));
}
/**
* camelCase to StudlyCaps
*
* @param string $str
* @return string
*/
static function camelToStudly($str) {
return ucfirst($str);
}
/**
* StudlyCaps to camelCase
*
* @param string $str
* @return string
*/
static function studlyToCamel($str) {
return lcfirst($str);
}
/**
* camelCase and StudlyCaps to snake_case
*
* @param string $str
* @return string
*/
static function camelToSnake($str) {
// Easy but slow implementation:
// return strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $str));
// Fast implementation without slow regex replace:
// Inspired by http://stackoverflow.com/a/1589544/807647
// Lowercase first letter.
$str[0] = strtolower($str[0]);
$len = strlen($str);
for ($i = 0; $i < $len; ++$i) {
// See if we have an uppercase character and replace; ord A = 65, Z = 90.
if (ord($str[$i]) > 64 && ord($str[$i]) < 91) {
// Replace uppercase of with underscore and lowercase.
$replace = '_' . strtolower($str[$i]);
$str = substr_replace($str, $replace, $i, 1);
// Increase length of class and position since we made the string longer.
++$len;
++$i;
}
}
return $str;
}
/**
* camelCase and StudlyCaps to snake_case
*
* @param string $str
* @return string
*/
static function studlyToSnake($str) {
return self::camelToSnake($str);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment