PHP How to Convert Camel Case to Snake Case Tutorial

Share this Article
Reading Time: 3 minutes
419 Views

Inside this article we will see the concept i.e PHP How to Convert Camel Case to Snake Case Tutorial. Article contains the classified information about PHP convert camel case to snake case.

If you are looking for a solution i.e Convert string to camel case in php then this article will help you a lot for this. Tutorial is super easy to understand and implement it in your code as well.

CamelCase is a way to separate the words in a phrase by making the first letter of each word capitalized and not using spaces.

“Camel Case” String Examples

camelCaseToSnakeCase, getPosts, getUsers

Snake case is a naming convention in which a developer replaces spaces between words with an underscore.

“Snake Case” String Examples

camel_case_to_snake_case, get_posts, get_users

Learn More –

Let’s get started.

Application Programming

Create a folder say string-convert in your localhost directory. Create a file index.php into it.

Open index.php file and write this code into it.

<?php
  
function camelCaseToSnakeCase($string) {
  
    return strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $string));
}
  
echo camelCaseToSnakeCase('camelCaseToSnakeCase');
echo "<br/>";
echo camelCaseToSnakeCase('getPosts');
echo "<br/>";
echo camelCaseToSnakeCase('getUsers');

Concept

We have created a user defined function in which we pass a string value. It uses PHP functions and regular expression pattern to convert string from Camel Case To Snake Case.

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

Application Testing

Now,

Open project into browser.

URL: http://localhost/string-convert/index.php

camel_case_to_snake_case

get_posts

get_users

We hope this article helped you to learn PHP How to Convert Camel Case to Snake Case Tutorial in a very detailed way.

Buy Me a Coffee

Online Web Tutor invites you to try Skillshare free for 1 month! Learn CakePHP 4, Laravel APIs Development, CodeIgniter 4, Node Js, etc into a depth level. Master the Coding Skills to Become an Expert in Web Development. So, Search your favourite course and enroll now. Click here to join.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Was this post helpful?

Learn Web Development Courses Risk Free @ $5 only.
Web Development Courses @ $5