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:
- Use a regular expression to match each uppercase letter that follows a lowercase letter.
- Replace each match with the lowercase letter followed by an underscore and the uppercase letter.
- 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.