Skip to content

Instantly share code, notes, and snippets.

@palemoky
Last active February 18, 2021 05:03
Show Gist options
  • Save palemoky/8c94f797440dffd19d0e9e3db6cb98a6 to your computer and use it in GitHub Desktop.
Save palemoky/8c94f797440dffd19d0e9e3db6cb98a6 to your computer and use it in GitHub Desktop.
蛇形变量名与驼峰变量名的相互转换
<?php
// 驼峰命名法转蛇形命名法
function camel2snake ($camel) {
if (false !== strpos($camel, '_')) {
return $camel;
}
$capitalLetters = range('A', 'Z');
for ($i=1; $i < strlen($camel) - 1; $i++) {
if (in_array($camel[$i], $capitalLetters)) {
$camel = str_replace($camel[$i], '_' . strtolower($camel[$i]), $camel);
}
}
return $camel;
}
// 蛇形命名法转驼峰命名法
function snake2camel ($snake, $lowerCamelCase = false) {
// 非下划线变量返回原值
if (false === strpos($snake, '_')) {
return $snake;
}
$snakeTitle = ucwords($snake, '_');
$upperCamelCase = str_replace('_', '', $snakeTitle);
return $lowerCamelCase ? lcfirst($upperCamelCase) : $upperCamelCase;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment