How to convert camelCase to snake_case and back
Short answer
Put an underscore before every capital letter and lowercase the string:
<?php
echo strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', 'userFirstName'));Output:
user_first_nameBack to camelCase
Capitalise the first letter of every word, remove the underscores and restore the lowercase first letter:
<?php
echo lcfirst(str_replace('_', '', ucwords('user_first_name', '_')));Output:
userFirstNameArray keys
This is how the keys of data coming from JavaScript are converted:
<?php
$input = ['firstName' => 'Anna', 'birthDate' => '1995-08-20'];
$result = [];
foreach ($input as $key => $value) {
$result[strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $key))] = $value;
}
echo json_encode($result);Output:
{"first_name":"Anna","birth_date":"1995-08-20"}Functions used in this recipe
- preg_replace — Replaces everything that matches a regular expression.
- preg_replace_callback — Replaces pattern matches with the result of a function.
- lcfirst — Makes the first letter of a string lowercase.