Laravel String Helper Function: snake

November 16, 2016 —John Koster

The snake helper method replaces all uppercase letters within the string with the lower cased variant prefixed with the given $delimiter. The only exception to this rule is that if the first character of the string is capitalized, it will be replaced by the lower cased variant without the $delimiter being prefixed. Because of this behavior, the entire string will be lower cased. The snake method trims extraneous whitespace from any string being converted.

The signature of the snake helper method is:

snake($value, $delimiter = '_')

Here are a few examples with the result above the function call in comments:

1use Illuminate\Support\Str;
2 
3// my_words
4echo Str::snake('MyWords');
5 
6// my-words
7echo Str::snake('MyWords', '-');
8 
9// m_y_w_o_r_d_s
10echo Str::snake('MYWORDS');
11 
12// this is _pretty_cool
13echo Str::snake('this_is_PrettyCool');

#snake_case($value, $delimiter = '_')

The snake_case function is a shortcut to calling Str::snake. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.