Created
March 6, 2012 00:45
-
-
Save skyzyx/1982523 to your computer and use it in GitHub Desktop.
Inflect between CapitalCase and 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 | |
/** | |
* Prepare the content for reformatting. | |
*/ | |
function prep_content($_string) | |
{ | |
// Strip all non-alphanumeric characters | |
$_string = preg_replace('/[^a-z0-9\-\_\s]/i', '', $_string); | |
// FMLCase => FML, Case | |
if (preg_match('/([A-Z][A-Z]+)([A-Z][a-z])/', $_string)) | |
{ | |
$_string = preg_replace('/([A-Z][A-Z]+)([A-Z][a-z])/', '$1 $2', $_string); | |
} | |
// camelCase => camel, Case | |
if (preg_match('/([a-z])([A-Z])/', $_string)) | |
{ | |
$_string = preg_replace('/([a-z])([A-Z])/', '$1 $2', $_string); | |
} | |
// snake_case => snake, case | |
if (preg_match('/([a-z])(_|-|\s+)([a-z])/i', $_string)) | |
{ | |
$_string = preg_replace('/([a-z])(_|-|\s+)([a-z])/i', '$1 $3', $_string); | |
} | |
// Numbers (prepended) | |
if (preg_match('/([0-9])([a-z])/i', $_string)) | |
{ | |
$_string = preg_replace('/([0-9])([a-z])/i', '$1 $2', $_string); | |
} | |
// Numbers (appended) | |
if (preg_match('/([a-z])([0-9])/i', $_string)) | |
{ | |
$_string = preg_replace('/([a-z])([0-9])/i', '$1 $2', $_string); | |
} | |
// Clean-up and split | |
$_string = trim($_string); | |
$_string = preg_replace('/\s+/', ' ', $_string); | |
return explode(' ', $_string); | |
} | |
/** | |
* Format the string as CapitalCase (aka, Upper Camel Case, Pascal Case, .NET Case, Studly Case). | |
*/ | |
public function capitalize($_string) | |
{ | |
$_pieces = prep_content($_string); | |
$string = implode(' ', $_pieces); | |
$string = strtolower($string); | |
$string = ucwords($string); | |
return str_replace(' ', '', $string); | |
} | |
/** | |
* Format the string as snake_case (aka, Underscore Case). | |
*/ | |
public function snakeize($_string) | |
{ | |
$_pieces = prep_content($_string); | |
$string = implode('_', $_pieces); | |
return strtolower($string); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of trying to go directly from one format into the other, it goes into a simple intermediate format -- space-delimited words.