How to convert CamelCase to snake_case in PHP (in a simpler way)?

1

How do I convert a string with CamelCase to snake_case into PHP as simply as possible?

Example:

CamelCase => camel_case
AjaxInfo  => ajax_info
    
asked by anonymous 04.07.2016 / 18:25

1 answer

4

Ready with a line has this one from the SOzão

$saida = ltrim(strtolower(preg_replace('/[A-Z]/', '_$0', $entrada )), '_');

The question is: What happens if you have ___ at the beginning?

It may be interesting to change the logic if it is always to start with a letter:

$saida = substr(strtolower(preg_replace('/[A-Z]/', '_$0', $entrada )), 1);

This here already guarantees the first character does not have _ using lcfirst :

$saida = strtolower( preg_replace(
    ["/([A-Z]+)/", "/_([A-Z]+)([A-Z][a-z])/"], ["_$1", "_$1_$2"], lcfirst($entrada) ) );


Remarks:

  • See these situations:

    LetraEMaiuscula 
    CodeIsHTML
    

    In the first case, using [a-z][A-Z] gives problem. In the second case, [a-z][A-Z] is better than just [A-Z] . If you need the second case you have to use an exchange in the format ([A-Z])([A-Z][a-z]) by $1_$2

  • What if I have spaces? I believe that if it is already well-formed CamelCase, it does not make sense to have spaces in the string, but if you need to change by _ , it is the case to add a str_replace(' ', '_', $valor ) as already noted Miguel in

04.07.2016 / 18:30