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

Viewed 1372

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?

2 Answers

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

Try using this code:

use Illuminate\Support\Str;

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

Hope this helps you

Related