How to convert PascalCase to pascal_case?

前端 未结 30 1670
北海茫月
北海茫月 2020-11-29 16:36

If I had:

$string = \"PascalCase\";

I need

\"pascal_case\"

Does PHP offer a function for this purpose?

30条回答
  •  盖世英雄少女心
    2020-11-29 17:30

    php does not offer a built in function for this afaik, but here is what I use

    function uncamelize($camel,$splitter="_") {
        $camel=preg_replace('/(?!^)[[:upper:]][[:lower:]]/', '$0', preg_replace('/(?!^)[[:upper:]]+/', $splitter.'$0', $camel));
        return strtolower($camel);
    
    }
    

    the splitter can be specified in the function call, so you can call it like so

    $camelized="thisStringIsCamelized";
    echo uncamelize($camelized,"_");
    //echoes "this_string_is_camelized"
    echo uncamelize($camelized,"-");
    //echoes "this-string-is-camelized"
    

提交回复
热议问题