How to Create URL Slug from String in PHP

The creation of a user-friendly URL is an essential part of the work with any website. It is crucial for the SEO of the webpage. Moreover, it helps the visitors to assure that the website is correct. Let’s consider the following URL:

http://www.example.com/this is the example demo page.

It will be rendered by the browser in this way:

http://www.example.com/this%20is%20the%20example%20demo%20page

So, you can notice, that the URL above can’t be considered as a user-friendly one. Hence, it is necessary to interchange the spaces with hyphens. Here is how it can be done:

<?php

function createUrlSlug($urlString)
{
    $slug = preg_replace('/[^A-Za-z0-9-]+/', '-', $urlString);
    return $slug;
}

echo createUrlSlug('this is the example demo page');
// This will return 'this-is-the-example-demo-page'
?>

A More Extended Version

In this section, we will show you an extensive version of the URL slug function. With the help of this version, you will manage to detect double hyphens and change them with one, as well as to deal with characters with any accents. Here is a detailed example:

<?php

function slugify($urlString)
{
  $search = ['Ș', 'Ț', 'ş', 'ţ', 'Ş', 'Ţ', 'ș', 'ț', 'î', 'â', 'ă', 'Î', ' ', 'Ă', 'ë', 'Ë'];
  $replace = ['s', 't', 's', 't', 's', 't', 's', 't', 'i', 'a', 'a', 'i', 'a', 'a', 'e', 'E'];
  $str = str_ireplace($search, $replace, strtolower(trim($urlString)));
  $str = preg_replace('/[^\w\d\-\ ]/', '', $str);
  $str = str_replace(' ', '-', $str);
  return preg_replace('/\-{2,}', '-', $str);
}

?>

About URL Slugs

A slug is considered a human-friendly, easy-readable identifier, applied for detecting a resource.

As a rule, a slug is used when one intends to refer to an item, upholding the capability of seeing what the given item is. A good slug should be unique, simple, as well as descriptive. The main point of using slugs is improving the SEO and helping the visitors to make sure the given website is correct.