How to convert Camelcase to snake_case in PHP (simply)?

Asked

Viewed 739 times

1

How do I convert a string with Camelcase for snake_case in PHP as simply as possible?

Example:

CamelCase => camel_case
AjaxInfo  => ajax_info
  • $saida = ltrim(strtolower(preg_replace('/[A-Z]/', '_$0', $entrada )), '_');

1 answer

5


Ready with a line has this one from Sozão

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

The question is, what happens if you do ___ at first?

But it can be interesting to change the logic if you’re always starting with a letter:

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

This one already guarantees the first character not having _ using lcfirst:

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


Remarks:

  • Look at these situations:

    LetraEMaiuscula 
    CodeIsHTML
    

    In the first case, use [a-z][A-Z] 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 a trade in the format ([A-Z])([A-Z][a-z]) for $1_$2

  • What if it has spaces? I believe that if it is already Camelcase well formed, it makes no sense to have spaces in the string, but if you need to exchange for _, is the case to add a str_replace(' ', '_', $valor ) as Miguel has already warned answer given.

  • The problem is if you have space. You should not replace it with '_'?

  • @Miguel good question. It depends on how the person will use it. I added a remark.

  • I realized of course that if it is Camelcase it is part of the brush that there are no spaces

  • @Miguel however I find valid his observation, fine tune, we never know how the person will use the code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.