Code Logo

Convert to Snake Case

Published at24 Jul 2026
PHP String Handling Easy 0 views
Like0

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

Example 1
Input
"hello world"
Output
"hello_world"
Example 2
Input
"PHP-is-FUN"
Output
"php_is_fun"
Example 3
Input
"already_snake"
Output
"already_snake"
Example 4
Input
""
Output
""
Example 5
Input
"Hello World"
Output
"hello_world"

Algorithm Flow

Recommendation Algorithm Flow for Convert to Snake Case
Recommendation Algorithm Flow for Convert to Snake Case

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 - Approach 1
<?php
function toSnakeCase($text) {
    return strtolower(str_replace([' ', '-'], '_', $text));
}