How do I convert a string
with CamelCase to snake_case into PHP as simply as possible?
Example:
CamelCase => camel_case
AjaxInfo => ajax_info
How do I convert a string
with CamelCase to snake_case into PHP as simply as possible?
Example:
CamelCase => camel_case
AjaxInfo => ajax_info
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