How to convert PascalCase to pascal_case?

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

    A shorter solution: Similar to the editor's one with a simplified regular expression and fixing the "trailing-underscore" problem:

    $output = strtolower(preg_replace('/(?

    PHP Demo | Regex Demo


    Note that cases like SimpleXML will be converted to simple_x_m_l using the above solution. That can also be considered a wrong usage of camel case notation (correct would be SimpleXml) rather than a bug of the algorithm since such cases are always ambiguous - even by grouping uppercase characters to one string (simple_xml) such algorithm will always fail in other edge cases like XMLHTMLConverter or one-letter words near abbreviations, etc. If you don't mind about the (rather rare) edge cases and want to handle SimpleXML correctly, you can use a little more complex solution:

    $output = ltrim(strtolower(preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $input)), '_');
    

    PHP Demo | Regex Demo

提交回复
热议问题