Oihana PHP

snake.php

Table of Contents

Functions

snake()  : string
Converts a string to snake_case (or a custom delimiter).

Functions

snake()

Converts a string to snake_case (or a custom delimiter).

snake(string|null $source[, string $delimiter = '_' ][, string|null $encoding = 'UTF-8' ]) : string

This function transforms camelCase, PascalCase, and space-separated words into snake case or any delimiter specified.

It uses an internal cache (via SnakeCache) to optimize repeated calls with the same input. The cache can be flushed by calling SnakeCache::flush().

Parameters
$source : string|null

The input string to convert.

$delimiter : string = '_'

The delimiter to use (default is underscore '_').

$encoding : string|null = 'UTF-8'

The encoding parameter is the character encoding. If it is omitted or null, the internal character encoding value will be used.

Tags
example

Basic usage

echo snake("helloWorld");  // Outputs: "hello_world"
echo snake("HelloWorld");  // Outputs: "hello_world"
echo snake("Hello World"); // Outputs: "hello_world"
echo snake("helloworld");  // Outputs: "helloworld"

With numbers

echo snake("helloWorld123"); // Outputs: "hello_world123"
echo snake("UserID42");      // Outputs: "user_id_42"

Unicode support

echo snake("helloWorldCafé"); // Outputs: "hello_world_café"
echo snake("CaféAuLait");     // Outputs: "café_au_lait"
echo snake("NaïveBayesian");  // Outputs: "naïve_bayesian"
echo snake("Emoji😊Test");    // Outputs: "emoji_😊_test"

Complex cases

echo snake("MyXMLParser");  // Outputs: "my_xml_parser"
echo snake("JSONToArray");  // Outputs: "json_to_array"
echo snake("hello world how are you"); // Outputs: "hello_world_how_are_you"

Custom delimiters

echo snake("helloWorld", "-"); // Outputs: "hello-world"
echo snake("helloWorld", "|"); // Outputs: "hello|world"
echo snake("helloWorld", " "); // Outputs: "hello world"

Edge cases

echo snake("");   // Outputs: ""
echo snake(null); // Outputs: ""

Clear the internal cache if needed

use oihana\core\strings\helpers\SnakeCache;
SnakeCache::flush();
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
string

The converted snake_case (or custom delimiter) string.


        
On this page

Search results