Laravel String Helper Function: studly_case

November 16, 2016 —John Koster

Studly caps is a way of formatting text with capital letters, according to some pattern. Laravel's pattern is to remove the following word separators and capitalize the first letter of each word it finds (while not affecting the case of any other letters):

  • Any number of spaces
  • The underscore _
  • The hyphen -

Let's take a look at a few examples to see how this would format a few example strings. The string returned will appear above the function call as a comment. In fact, all of the function calls below will return the string MyWords:

1<?php
2 
3use Illuminate\Support\Str;
4 
5// MyWords
6echo Str::studly('my words');
7 
8// MyWords
9echo Str::studly('my words');
10 
11// MyWords
12echo Str::studly(' my-words');
13 
14// MyWords
15echo Str::studly(' my-words_');
Pascal Case

Laravel's studly method can also be used to generate Pascal Cased style strings. Both styles are the same as camel case with the first letter capitalized.

Because the studly method does not affect the case of any letters after the first letter, we can arrive at output that some users might not expect. Again, the output string will appear above the method call in a comment.

1use Illuminate\Support\Str;
2 
3// MyWORDS
4echo Str::studly('my-WORDS');
5 
6// MYWORDS
7echo Str::studly('MY_WORDS');

#studly_case($value)

The studly_case function is a shortcut to calling Str::studly. 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.