If I had:
$string = \"PascalCase\";
I need
\"pascal_case\"
Does PHP offer a function for this purpose?>
Ported from Ruby's String#camelize
and String#decamelize
.
function decamelize($word) {
return preg_replace(
'/(^|[a-z])([A-Z])/e',
'strtolower(strlen("\\1") ? "\\1_\\2" : "\\2")',
$word
);
}
function camelize($word) {
return preg_replace('/(^|_)([a-z])/e', 'strtoupper("\\2")', $word);
}
One trick the above solutions may have missed is the 'e' modifier which causes preg_replace
to evaluate the replacement string as PHP code.