camelCase to dash - two capitals next to each other

前端 未结 2 1031
情话喂你
情话喂你 2021-01-01 23:24

I\'m using this function to convert CamelCase to dashed string:

function camel2dashed($className) {
    return strtolower(preg_replace(\'/([^A-Z-])([A-Z])/\'         


        
相关标签:
2条回答
  • 2021-01-01 23:48

    You don't need a lookahead assertion to do this if you know that your string doesn't start with an upper-case letter, you can just insert a hyphen before every upper-case letter like this:

    function camel2dashed($className) {
        return strtolower(preg_replace('/([A-Z])/', '-$1', $className));
    }
    

    This still won't handle cases like @sfjedi's "companyHQ" -> "company-hq". For that you'd have to explicitly test for permitted capitalized substrings that shouldn't be split, or specify some generic rules (e.g. don't prepend hyphen before last character).

    You can find some more sophisticated alternatives in the answers to this virtual duplicate question.

    0 讨论(0)
  • 2021-01-02 00:01

    Use a lookahead assertion:

    function camel2dashed($className) {
        return strtolower(preg_replace('/([a-zA-Z])(?=[A-Z])/', '$1-', $className));
    }
    

    See it working online: ideone

    0 讨论(0)
提交回复
热议问题