How to convert PascalCase to pascal_case?

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

    A version that doesn't use regex can be found in the Alchitect source:

    decamelize($str, $glue='_')
    {
        $counter  = 0;
        $uc_chars = '';
        $new_str  = array();
        $str_len  = strlen($str);
    
        for ($x=0; $x<$str_len; ++$x)
        {
            $ascii_val = ord($str[$x]);
    
            if ($ascii_val >= 65 && $ascii_val <= 90)
            {
                $uc_chars .= $str[$x];
            }
        }
    
        $tok = strtok($str, $uc_chars);
    
        while ($tok !== false)
        {
            $new_char  = chr(ord($uc_chars[$counter]) + 32);
            $new_str[] = $new_char . $tok;
            $tok       = strtok($uc_chars);
    
            ++$counter;
        }
    
        return implode($new_str, $glue);
    }
    

提交回复
热议问题