How to convert PascalCase to pascal_case?

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

    The worst answer on here was so close to being the best(use a framework). NO DON'T, just take a look at the source code. seeing what a well established framework uses would be a far more reliable approach(tried and tested). The Zend framework has some word filters which fit your needs. Source.

    here is a couple of methods I adapted from the source.

    function CamelCaseToSeparator($value,$separator = ' ')
    {
        if (!is_scalar($value) && !is_array($value)) {
            return $value;
        }
        if (defined('PREG_BAD_UTF8_OFFSET_ERROR') && preg_match('/\pL/u', 'a') == 1) {
            $pattern     = ['#(?<=(?:\p{Lu}))(\p{Lu}\p{Ll})#', '#(?<=(?:\p{Ll}|\p{Nd}))(\p{Lu})#'];
            $replacement = [$separator . '\1', $separator . '\1'];
        } else {
            $pattern     = ['#(?<=(?:[A-Z]))([A-Z]+)([A-Z][a-z])#', '#(?<=(?:[a-z0-9]))([A-Z])#'];
            $replacement = ['\1' . $separator . '\2', $separator . '\1'];
        }
        return preg_replace($pattern, $replacement, $value);
    }
    function CamelCaseToUnderscore($value){
        return CamelCaseToSeparator($value,'_');
    }
    function CamelCaseToDash($value){
        return CamelCaseToSeparator($value,'-');
    }
    $string = CamelCaseToUnderscore("CamelCase");
    

提交回复
热议问题