how to create slug in php

Create slug in php

The URL slug always will play an important role in SEO for website. So it is very imoratant to pass slug in URL’s.

Having a user friendly URL is user important not just for SEO but also to help the visitors know that the website they are on is correct.

If you have spaces in your URL they will be replaced by %20 so if you are linking to the page. programming blog
The browser would actual render this URL as

As you can see this isn’t the most user friendly URL so you need to be able to replace the spaces with hyphens.

Here is a PHP snippet that will replace all spaces with a hyphen.

Extended URL Slug Version

Here is an extended version of the URL slug function. I always work with UTF-8 but you can obviously use any character encoding recognized by your system. The piñata text is now transliterated into a-pinata-is-a-paper-container-filled-with-candy. Lovable.

If they are not Spanish, users will hardly search your site for the word piñata, they will most likely search for pinata. So you may want to store both versions in your database. You may have a title field with the actual displayed text and a slug field containing its ascii version counterpart.

We can add a delimiter parameter to our function so we can use it to generate both clean urls and slugs

There’s one more thing. The string “I’m back!” is converted to i-m-back. This may or may not be an issue depending on your application.

Thanks!. If you like this article don’t forget to share and comment.