Get "PHP 8 in a Nuthshell" (Now with PHP 8.4)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Make any string studly case using Str::headline() in Laravel 8.x

Strings are tricky things to work with when it comes to programming. But thankfully, Laravel provides a lot of helper methods that can fulfill almost all the use-cases you might have when you’re working with strings.

In addition to all these string helper methods, Laravel will have one more method that can solve many problems all at once.

The Str::headline() method

According to this PR, Laravel 8.x will be included with this new method called Str::headline() using which it’s possible to make any string into the studly case. This is useful when you want to extract out a title-like structure out of a string.

Here are a few examples of how it works.

use Illuminate\Support\Str;

echo Str::headline('php-is-great');
// Outputs: Php Is Great

echo Str::headline('php_is_great');
// Outputs: Php Is Great

echo Str::headline('phpIs_great');
// Outputs: Php Is Great

echo Str::headline('php - is _great');
// Outputs: Php Is Great

As you can tell, this method works perfectly fine under several different use cases. If you want to see all the examples, you can check out the tests for this method.

Apart from making studly case strings, it can transform PHP class names to the studly case as well which is pretty fantastic!

echo Str::headline(
    class_basename(\App\Events\VoiceRecordingStored::class)
);
// Outputs: "Voice Recording Stored"
Learn the fundamentals of PHP 8 (including 8.1, 8.2, 8.3, and 8.4), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

Like this article?

Buy me a coffee

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?