How to convert PascalCase to pascal_case?

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

    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.

提交回复
热议问题