Search

Laravel 5.5 String Helper Function: studly

November 27, 2017 —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 -

#Signature

The signature of the studly method is:

1public static function studly(
2 $value
3 );

#Example Use

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:

1use Illuminate\Support\Str;
2 
3// MyWords
4echo Str::studly('my words');
5 
6// MyWords
7echo Str::studly('my words');
8 
9// MyWords
10echo Str::studly(' my-words');
11 
12// MyWords
13echo 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');

#Global studly_case Helper Function

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.