Symfony

How to generate a slug with the Symfony string component

The String component provides a single object-oriented API to work with three “unit systems” of strings: bytes, code points, and grapheme clusters.

This code example shows how to generate a slug with the Symfony string component. Usually, when using the Symfony string component, we use the u() shortcut. Not in this case, there is a dedicated class for this purpose. It’s easy to use and test as it doesn’t have dependencies. The most common parameter, the separator, is available as the second argument of the slug() function. You can also get the service with the SluggerInterface type hint. Be careful that the final string isn’t in lowercase by default. You can also use the Doctrine sluggable extension for your entities, which is convenient.

$slugger = new AsciiSlugger();
$articleTitle = 'Generating a slug with the Symfony string component';
$slug = $slugger->slug($articleTitle)->lower();

You can read more about the Symfony String component here.