Created
October 3, 2014 13:49
-
-
Save khoand0000/047778e629f26d12a086 to your computer and use it in GitHub Desktop.
convert naming convention (PascalCased, camelCased, with_underscores) to each other
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 | |
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