How to Convert Camel Case to Snake Case in PHP?

By Hardik Savani May 14, 2024 Category : PHP

Hey,

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, let's follow a few steps to create an example of convert camel case to snake case php.

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:

We need:

"camelCaseToSnakeCase" into "camel_case_to_snake_case"

"getPosts" into "get_posts"

"getUsers" into "get_users"

So, let's see below example code and let's check it.

Example: index.php

<?php

/**

* Write code on Method

*

* @return response()

*/

function camelCaseToSnakeCase($string)

{

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

}

echo camelCaseToSnakeCase('camelCaseToSnakeCase');

echo camelCaseToSnakeCase('getPosts');

echo camelCaseToSnakeCase('getUsers');

Output:

camel_case_to_snake_case

get_posts

get_users

I hope it can help you...

Tags :
Shares