How to convert PascalCase to pascal_case?

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

    A concise solution and can handle some tricky use cases:

    function decamelize($string) {
        return strtolower(preg_replace(['/([a-z\d])([A-Z])/', '/([^_])([A-Z][a-z])/'], '$1_$2', $string));
    }
    

    Can handle all these cases:

    simpleTest => simple_test
    easy => easy
    HTML => html
    simpleXML => simple_xml
    PDFLoad => pdf_load
    startMIDDLELast => start_middle_last
    AString => a_string
    Some4Numbers234 => some4_numbers234
    TEST123String => test123_string
    hello_world => hello_world
    hello__world => hello__world
    _hello_world_ => _hello_world_
    hello_World => hello_world
    HelloWorld => hello_world
    helloWorldFoo => hello_world_foo
    hello-world => hello-world
    myHTMLFiLe => my_html_fi_le
    aBaBaB => a_ba_ba_b
    BaBaBa => ba_ba_ba
    libC => lib_c
    

    You can test this function here: http://syframework.alwaysdata.net/decamelize

提交回复
热议问题