How to convert PascalCase to pascal_case?

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

    I had a similar problem but couldn't find any answer that satisfies how to convert CamelCase to snake_case, while avoiding duplicate or redundant underscores _ for names with underscores, or all caps abbreviations.

    Th problem is as follows:

    CamelCaseClass            => camel_case_class
    ClassName_WithUnderscores => class_name_with_underscore
    FAQ                       => faq
    

    The solution I wrote is a simple two functions call, lowercase and search and replace for consecutive lowercase-uppercase letters:

    strtolower(preg_replace("/([a-z])([A-Z])/", "$1_$2", $name));
    

提交回复
热议问题