How to convert PascalCase to pascal_case?

前端 未结 30 1598
北海茫月
北海茫月 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:09

    The direct port from rails (minus their special handling for :: or acronyms) would be

    function underscore($word){
        $word = preg_replace('#([A-Z\d]+)([A-Z][a-z])#','\1_\2', $word);
        $word = preg_replace('#([a-z\d])([A-Z])#', '\1_\2', $word);
        return strtolower(strtr($word, '-', '_'));
    }
    

    Knowing PHP, this will be faster than the manual parsing that's happening in other answers given here. The disadvantage is that you don't get to chose what to use as a separator between words, but that wasn't part of the question.

    Also check the relevant rails source code

    Note that this is intended for use with ASCII identifiers. If you need to do this with characters outside of the ASCII range, use the '/u' modifier for preg_matchand use mb_strtolower.

提交回复
热议问题