PASSWORD RESET

Your destination for complete Tech news

PHP

How to convert Camel Case to Snake Case in PHP?

2.05K 0
< 1 min read

In PHP, you can convert a string from camel case or Pascal case to snake case using the strtolower() and preg_replace() functions. Here’s an example:

function camelCaseToSnakeCase($str) {
  $snakeCase = strtolower(preg_replace('/([a-z])([A-Z])/', '$1_$2', $str));
  return $snakeCase;
}

In this example, we define a function called camelCaseToSnakeCase() that takes a camel case or Pascal case string as its argument. The function converts the string to snake case using the following steps:

  1. Use a regular expression to match each uppercase letter that follows a lowercase letter.
  2. Replace each match with the lowercase letter followed by an underscore and the uppercase letter.
  3. Convert the resulting string to lowercase using the strtolower() function.

For example, if you call camelCaseToSnakeCase('myVariableName'), the function will return 'my_variable_name'.

Note that this function only works for strings that use the standard camel case or Pascal case conventions where the first letter of the first word is lowercase and the first letter of each subsequent word is uppercase. If your strings use a different convention, you may need to modify the regular expression to match the appropriate pattern.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.