Last active
May 19, 2016 12:50
-
-
Save linxlad/5de2f47bc20cbed08be94f9e20f0bc00 to your computer and use it in GitHub Desktop.
CamelCase to underscore with number support.
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 | |
/** | |
* @param $input | |
* @param bool $lowercase | |
* @param int $numbers 0 = No numbers, 1 = Numbers and 2 = Number with underscores | |
* | |
* @return mixed | |
*/ | |
function camelCaseToUnderscore( | |
$input, | |
$lowercase = true, | |
$numbers = self::NO_NUMBERS | |
) { | |
$match = [ | |
"/([A-Z]+)/", | |
"/_([A-Z]+)([A-Z][a-z])/", | |
]; | |
$replace = [ | |
"_$1", | |
"_$1_$2", | |
]; | |
if (1 === $numbers) { | |
$match = array_merge($match, [ | |
"/([0-9]+)/", | |
]); | |
$replace = array_merge($replace, [ | |
"_$1", | |
]); | |
} elseif (2 === $numbers) { | |
$match = array_merge($match, [ | |
"/(.{1})$/", | |
"/\d(?!$)/", | |
]); | |
$replace = array_merge($replace, [ | |
"_$0", | |
"_$0", | |
]); | |
} | |
$result = preg_replace($match, $replace, lcfirst($input)); | |
if ($lowercase) { | |
$result = strtolower($result); | |
} | |
return $result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment