Php Convert Camel Case To Snake Case

The coding style for one project may use CamelCase for variables, while another may use under_scores. Here are some Vim procedures to switch between CamelCase and under_score variable names.

32 Answers 32 Sorted by:

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending. 1

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

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 dont mind about the (rather rare) edge cases and want to handle SimpleXML correctly, you can use a little more complex solution:

Try this on for size:

Output:

This implements the following rules:

  • A sequence beginning with a lowercase letter must be followed by lowercase letters and digits;
  • A sequence beginning with an uppercase letter can be followed by either:
    • one or more uppercase letters and digits (followed by either the end of the string or an uppercase letter followed by a lowercase letter or digit ie the start of the next sequence); or
    • one or more lowercase letters or digits.
  • A concise solution and can handle some tricky use cases:

    Can handle all these cases:

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

    The Symfony Serializer Component has a CamelCaseToSnakeCaseNameConverter that has two methods normalize() and denormalize(). These can be used as follows:

    Ported from Rubys String#camelize and String#decamelize.

    One trick the above solutions may have missed is the e modifier which causes preg_replace to evaluate the replacement string as PHP code.

    Most solutions here feel heavy handed. Heres what I use:

  • lcfirst($camelCase) will lower the first character (avoids CamelCASE converted output to start with an underscore)
  • [A-Z] finds capital letters
  • + will treat every consecutive uppercase as a word (avoids CamelCASE to be converted to camel_C_A_S_E)
  • Second pattern and replacement are for ThoseSPECCases -> those_spec_cases instead of those_speccases
  • strtolower([…]) turns the output to lowercases
  • php does not offer a built in function for this afaik, but here is what I use

    the splitter can be specified in the function call, so you can call it like so

    “CamelCase” to “camel_case”:

    or:

    You need to run a regex through it that matches every uppercase letter except if it is in the beginning and replace it with underscrore plus that letter. An utf-8 solution is this:

    If you are not sure what case your string is, better to check it first, because this code assumes that the input is camelCase instead of underscore_Case or dash-Case, so if the latters have uppercase letters, it will add underscores to them.

    The accepted answer from cletus is way too overcomplicated imho and it works only with latin characters. I find it a really bad solution and wonder why it was accepted at all. Converting TEST123String into test123_string is not necessarily a valid requirement. I rather kept it simple and separated ABCccc into a_b_cccc instead of ab_cccc because it does not lose information this way and the backward conversion will give the exact same string we started with. Even if you want to do it the other way it is relative easy to write a regex for it with positive lookbehind (? or two regexes without lookbehind if you are not a regex expert. There is no need to split it up into substrings not to mention deciding between strtolower and lcfirst where using just strtolower would be completely fine.

    If you are looking for a PHP 5.4 version and later answer here is the code:

    I had a similar problem but couldnt find any answer that satisfies how to convert CamelCase to snake_case, while avoiding duplicate or redundant underscores _ for names with underscores, or all caps abbreviations.

    Th problem is as follows:

    The solution I wrote is a simple two functions call, lowercase and search and replace for consecutive lowercase-uppercase letters:

    Short solution:

    Not fancy at all but simple and speedy as hell:

    A version that doesnt use regex can be found in the Alchitect source:

    So here is a one-liner:

    danielstjules/Stringy provieds a method to convert string from camelcase to snakecase.

    Laravel 5.6 provides a very simple way of doing this:

    What it does: if it sees that there is at least one capital letter in the given string, it uses a positive lookahead to search for any character (.) followed by a capital letter ((?=[A-Z])). It then replaces the found character with its value followed by the separactor _.

    The direct port from rails (minus their special handling for :: or acronyms) would be

    Knowing PHP, this will be faster than the manual parsing thats happening in other answers given here. The disadvantage is that you dont get to chose what to use as a separator between words, but that wasnt part of the question.

    Also check the relevant rails source code

    Note that this is intended for use with ASCII identifiers. If you need to do this with characters outside of the ASCII range, use the /u modifier for preg_matchand use mb_strtolower.

    Here is my contribution to a six-year-old question with god knows how many answers...

    It will convert all words in the provided string that are in camelcase to snakecase. For example "SuperSpecialAwesome and also FizBuzz καιΚάτιΑκόμα" will be converted to "super_special_awesome and also fizz_buzz και_κάτι_ακόμα".

    Yii2 have the different function to make the word snake_case from CamelCase.

    If you are not using Composer for PHP you are wasting your time.

    Use Symfony String

    The worst answer on here was so close to being the best(use a framework). NO DONT, just take a look at the source code. seeing what a well established framework uses would be a far more reliable approach(tried and tested). The Zend framework has some word filters which fit your needs. Source.

    here is a couple of methods I adapted from the source.

    There is a library providing this functionality:

    If you use Laravel framework, you can use just snake_case() method.

    This is one of shorter ways:

    How to de-camelize without using regex:

    An edit:

    How would I do that in 2019:

    PHP 7.3 and before:

    And with PHP 7.4+:

    Its easy using the Filter classes of the Zend Word Filters:

    The open source TurboCommons library contains a general purpose formatCase() method inside the StringUtils class, which lets you convert a string to lots of common case formats, like CamelCase, UpperCamelCase, LowerCamelCase, snake_case, Title Case, and many more.

    To use it, import the phar file to your project and:

    Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!
  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.
  • To learn more, see our tips on writing great answers. Draft saved Draft discarded

    This tutorial shows you how to convert camel case to snake case in php. We will use php convert camelcase to snake case. you will learn laravel convert camelcase to snake case. I explained simply step by step php convert camelcase to snake case. So, lets follow a few steps to create an example of convert camel case to snake case php.

    Im a full-stack developer, entrepreneur and owner of Aatman Infotech. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap from the early stage. I believe in Hardworking and Consistency.

    I will give you a very short example of how to convert a camel case to a snake case in php. you can see the below camel case string into the snake_case example with output:

    Converting PHP variables[]

    This is a simple procedure to change variables names from $this_variable_style to $thisVariableStyle.

    The commands below define these mappings:

  • + Find the next $variable_with_underscores.
  • _ Convert the next underscore on the current line.
  • When required, you can yank the following lines in Vim (on the first line, type 2Y), then execute them (type @") to map the + and _ keys.

    Now you can press + to search for the next $variable_with_underscores, then press _ to find and delete the next underscore and toggle the case of the next character. Repeatedly press _ until all underscores are processed, then press + to find the next variable. For example, you may type +__+_+___ to skip through a file.

    The simple procedure above is suitable for manually changing a small number of variables, while inspecting each change. Using a substitute, the process can be automated. The following command will change all variables names from $this_variable_style to $thisVariableStyle:

    If wanted, the v (very magic) option can be used to reduce the number of backslashes, and the conventional / can be used as the delimiter instead of #. The following command is equivalent to the above:

    FAQ

    How do you convert a camelCase?

    The toUpperCase() and toLowerCase() methods are used to convert the string character into upper case and lower case respectively. Example 1: This example uses reduce , toLowerCase() and toUpperCase() methods to convert a string into camelCase.

    How do you change to snake case?

    Screaming snake case is used for variables. Scripting languages, as demonstrated in the Python style guide, recommend snake case in the instances where C-based languages use camel case.

    Is snake case better than camel case?

    Screaming snake case is used for variables. Scripting languages, as demonstrated in the Python style guide, recommend snake case in the instances where C-based languages use camel case.

    Is Snake Case lower case?

    Screaming snake case is used for variables. Scripting languages, as demonstrated in the Python style guide, recommend snake case in the instances where C-based languages use camel case.

    Related Posts