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.
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"
👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I write and want me to continue doing the same, I would like you buy me some coffees. I'd highly appreciate that. Cheers!