Skip to content

Instantly share code, notes, and snippets.

@linxlad
Last active May 19, 2016 12:50
Show Gist options
  • Save linxlad/5de2f47bc20cbed08be94f9e20f0bc00 to your computer and use it in GitHub Desktop.
Save linxlad/5de2f47bc20cbed08be94f9e20f0bc00 to your computer and use it in GitHub Desktop.
CamelCase to underscore with number support.
<?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