How to Convert Camel Case to Snake Case in PHP?

In this blog, we are going to convert camel cases to snake cases in PHP. This will be going to be simple and easy as I will explain with examples. 

Let's start,


Here is what we will be going to do,


"camelCaseToSnakeCase" into "camel_case_to_snake_case"


"getData" into "get_data"


"getUsers" into "get_users"


So let's convert this by using PHP code,


<?php

  

/**

 * Write code on Method

 *

 * @return response()

 */

function camelCaseToSnakeCase($string)

{

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

}

  

echo camelCaseToSnakeCase('camelCaseToSnakeCase');

echo camelCaseToSnakeCase('getData');

echo camelCaseToSnakeCase('getUsers');



Output:


camel_case_to_snake_case


get_data


get_users


I hope this will help in your program. Let me know in comments if you have any doubts.