How to convert PascalCase to snake_case?

A shorter solution: Similar to the editor’s one with a simplified regular expression and fixing the “trailing-underscore” problem:

$output = strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $input));

PHP Demo |
Regex Demo


Note that cases like SimpleXML will be converted to simple_x_m_l using the above solution. That can also be considered a wrong usage of camel case notation (correct would be SimpleXml) rather than a bug of the algorithm since such cases are always ambiguous – even by grouping uppercase characters to one string (simple_xml) such algorithm will always fail in other edge cases like XMLHTMLConverter or one-letter words near abbreviations, etc. If you don’t mind about the (rather rare) edge cases and want to handle SimpleXML correctly, you can use a little more complex solution:

$output = ltrim(strtolower(preg_replace('/[A-Z]([A-Z](?![a-z]))*/', '_$0', $input)), '_');

PHP Demo |
Regex Demo

Leave a Comment