Skip to content

Instantly share code, notes, and snippets.

@khoand0000
Created October 3, 2014 13:49
Show Gist options
  • Save khoand0000/047778e629f26d12a086 to your computer and use it in GitHub Desktop.
Save khoand0000/047778e629f26d12a086 to your computer and use it in GitHub Desktop.
convert naming convention (PascalCased, camelCased, with_underscores) to each other
<?php
class NamingConventionConverter {
/**
* convert camelCasedString or PascalCasedString to underscores_string
* ref: http://stackoverflow.com/questions/1993721/how-to-convert-camelcase-to-camel-case
* @param string $word camelCasedString or PascalCasedString
* @return string underscores_string
*/
public static function camel2Underscores($word) {
return preg_replace(
'/(^|[a-z])([A-Z])/e',
'strtolower(strlen("\\1") ? "\\1_\\2" : "\\2")',
$word
);
}
/**
* convert underscores_string to PascalCasedString
* @param string $word underscores_string
* @return string PascalCasedString
*/
public static function underscores2Pascal($word) {
return preg_replace('/(^|_)([a-z])/e', 'strtoupper("\\2")', $word);
}
/**
* convert underscores_string to camelCasedString
* @param string $word underscores_string
* @return string camelCasedString
*/
public static function underscores2Camel($word) {
return ucfirst(underscores2Pascal($word));
}
/**
* convert camelCasedString to words string
* @param string $word camelCasedString
* @return string words string
*/
public static function camel2Words($word) {
return preg_replace(
'/(^|[a-z])([A-Z])/e',
'strlen("\\1") ? "\\1 \\2" : "\\2"',
$word
);
}
/**
* convert camelCasedString to ucwords(words string) (Uppercase the first character of each word in a string)
* @param string $word camelCasedString
* @return string ucwords(words string)
*/
public static function camel2Ucwords($word) {
return ucwords(camel2Words($word));
}
/**
* convert camelCasedString to ucfirst(words string) (a string's first character uppercase)
* @param string $word camelCasedString
* @return string ucfirst(words string)
*/
public static function camel2Ucfirst($word) {
return ucfirst(strtolower(camel2Words($word)));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment