How to convert PascalCase to pascal_case?

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

    Not fancy at all but simple and speedy as hell:

    function uncamelize($str) 
    {
        $str = lcfirst($str);
        $lc = strtolower($str);
        $result = '';
        $length = strlen($str);
        for ($i = 0; $i < $length; $i++) {
            $result .= ($str[$i] == $lc[$i] ? '' : '_') . $lc[$i];
        }
        return $result;
    }
    
    echo uncamelize('HelloAWorld'); //hello_a_world
    

提交回复
热议问题