Niels Bosman
Niels Bosman

Reputation: 956

How can I convert PascalCase string to a usable slug in Laravel 7 with PHP?

I currently have a variable with the value of "ExtraOption". I wonder if it is possible (with Laravel helpers perhaps) convert this string into a usable slug. For example: "extra-option".

Can anyone help me out with a single, clean solution?

Upvotes: 5

Views: 3570

Answers (2)

W Kristianto
W Kristianto

Reputation: 9303

You can use Str::kebab() method to converts the given string to kebab-case:

use Illuminate\Support\Str;

$converted = Str::kebab('ExtraOption');

// extra-option

Laravel 7 has new feature Fluent String Operations which provides a variety of helpful string manipulation functions.

kebab

The kebab method converts the given string to kebab-case:

use Illuminate\Support\Str;

$converted = Str::of('ExtraOption')->kebab();

// extra-option

Upvotes: 7

Malkhazi Dartsmelidze
Malkhazi Dartsmelidze

Reputation: 4992

Try using this code:

use Illuminate\Support\Str;

...
Str::slug(implode(' ', preg_split('/(?=[A-Z])/', 'camelCaseToSlug')))
> camel-case-to-slug
...

Hope this helps you

Upvotes: 2

Related Questions