How to remove a camel without using regular expressions:
function decamelize($str, $glue = '_') { $capitals = []; $replace = []; foreach(str_split($str) as $index => $char) { if(!ctype_upper($char)) { continue; } $capitals[] = $char; $replace[] = ($index > 0 ? $glue : '') . strtolower($char); } if(count($capitals) > 0) { return str_replace($capitals, $replace, $str); } return $str; }
Editing:
How would I do it in 2019:
function toSnakeCase($str, $glue = '_') { return preg_replace_callback('/[AZ]/', function ($matches) use ($glue) { return $glue . strtolower($matches[0]); }, $str); }
And when PHP 7.4 comes out:
function toSnakeCase($str, $glue = '_') { return preg_replace_callback('/[AZ]/', fn($matches) => $glue . strtolower($matches[0]), $str); }
baldrs Apr 09 '13 at 12:30 2013-04-09 12:30
source share