Convert to Snake Case
Write a PHP function that converts a given string to snake_case. Snake case replaces all spaces and hyphens with underscores and converts all letters to lowercase. For example, "Hello World" becomes "hello_world".
Replace spaces and hyphens with underscores using str_replace(). Convert to lowercase with strtolower(). Combine these operations to transform any phrase into snake_case format.
Edge cases include empty strings (return ''), strings already in snake_case, strings with multiple consecutive spaces, and strings with mixed case and punctuation.
Snake case is commonly used in programming for variable and function names. The conversion process replaces word separators with underscores and lowercases all letters. PHP's str_replace() accepts arrays for batch replacement operations.
Converting between naming conventions (camelCase, snake_case, kebab-case) is common when working with multiple programming languages or data formats. PHP's str_replace() handles simple character swaps efficiently.
The strtolower() function ensures consistent casing regardless of input format. For more complex conversions involving camelCase boundaries (where a lowercase letter is followed by uppercase), regular expressions with preg_replace() would be needed to insert separators before capital letters.
Example Input & Output
Algorithm Flow

Solution Approach
Use str_replace([' ', '-'], '_', $text) to replace spaces and hyphens with underscores. Then apply strtolower() to convert to lowercase. The str_replace function accepts an array of search values and replaces them with the given replacement.
For more complex conversions involving multiple delimiter types, preg_replace('/[\s-]+/', '_', $text) can replace any whitespace sequence or hyphen with a single underscore.
Edge cases include empty strings (return ''), already snake_case strings, and strings with multiple spaces between words.
The time complexity is O(n). Space complexity is O(n).
Best Answers
<?php
function toSnakeCase($text) {
return strtolower(str_replace([' ', '-'], '_', $text));
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
