知道什么是蛇形命名法(snake case)和驼峰命名法(camel case)吗?
snake case类似于这样: file_name、 line_number、 my_first_program
camel case类似于这样: fileName、 lineNumber、 myFirstProgram

使用PHP内置函数实现

// 蛇形命名转换为驼峰命名
function SnakeToLowerCamel($value){
    $value = ucwords(str_replace(['_', '-'], ' ', $value));
    $value = str_replace(' ', '', $value);
    return lcfirst($value);
}

// 驼峰命名转换为蛇形命名
function CamelToSnake($value){
    // 以 UTF-8 模式删除空字符
    $value = preg_replace('/\s+/u', '', $value);
    // “?=”为正向预查,在任何开始匹配圆括号内的正则表达式模式的位置来匹配搜索字符串
    // 这里的正则表达式匹配所有大写字符的前一个字符
    $value = strtolower(preg_replace('/(.)(?=[A-Z])/u', "$1_", $value));
    return $value;
}

// 附加一个:蛇形命名转换为大驼峰命名(首字母大写 如: FileName、 LineNumber、 MyFirstProgram)
function SnakeToUpperCamel($value){
    $value = ucwords(str_replace(['_', '-'], ' ', $value));
    $value = str_replace(' ', '', $value);
    return $value;
}

标签: php

添加新评论