Categories: PHP

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.

http://www.example.com/17educations 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.

function create_url_slug($string){
   $slug=preg_replace('/[^A-Za-z0-9-]+/', '-', $string);
   return strtolower($slug);

echo create_url_slug('17educations author is marimuthu');
// This will return '17educations-author-is-marimuthu'

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

setlocale(LC_ALL, 'en_US.UTF8');
function slugify($str, $delimiter='-') {
    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
    $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
    $clean = strtolower(trim($clean, '-'));
    $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

    return $clean;

echo slugify("hi! Im A piñata is a paper container filled with candy.", '-');
// returns: a pinata is a paper container filled with candy

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.


Marimuthu :