To convert a string from CamelCase to snake_case in PHP, you can use the following function:
function camelCaseToSnakeCase($input) {
return strtolower(preg_replace('/(?<=\\w)([A-Z])/', '_\\1', $input));
}
Here’s how the function works:
(?<=\\w)
is a positive lookbehind that ensures there is a word character (letter, digit, or underscore) before the match. This is to avoid inserting underscores at the beginning of the string.([A-Z])
is a capturing group that matches any uppercase letter (A to Z).'_\\1'
is the replacement pattern, which inserts an underscore followed by the first capturing group (the uppercase letter) where the match occurred.
Let’s see some examples:
echo camelCaseToSnakeCase('helloWorld'); // Output: "hello_world"
echo camelCaseToSnakeCase('helloWorldExample'); // Output: "hello_world_example"
echo camelCaseToSnakeCase('anotherExample123'); // Output: "another_example123"
The function will convert the CamelCase input to snake_case as expected. Note that numbers are not affected, and only uppercase letters are replaced with underscores followed by the lowercase version of the letter.