PHP Snippet to Create SEO Friendly URL Slug from Title

As you know slugs, SEO friendly URLs, clean URLs, permalinks, etc. are easy to read (for humans and search engines).

If you have spaces in your URL they will be replaced by %20 so if you are linking to the page. is the example demo page

The browser would actual render this URL as

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

Source Code:

* Generate a URL friendly "slug" from a given string.
* @param  string  $title
* @param  string  $separator
* @return string
function slug($title, $separator = '-')
    // convert String to Utf-8 Ascii
    $title = iconv(mb_detect_encoding($title, mb_detect_order(), true), "UTF-8", $title);

    // Convert all dashes/underscores into separator
    $flip = $separator == '-' ? '_' : '-';

    $title = preg_replace('!['.preg_quote($flip).']+!u', $separator, $title);

    // Remove all characters that are not the separator, letters, numbers, or whitespace.
    $title = preg_replace('![^'.preg_quote($separator).'\pL\pN\s]+!u', '', mb_strtolower($title));

    // Replace all separator characters and whitespace by a single separator
    $title = preg_replace('!['.preg_quote($separator).'\s]+!u', $separator, $title);

    return trim($title, $separator);

Here is Example how you can use this php snipet to convert string title to url slug.

Output / Usage:

$string = "PHP Function to Create SEO Friendly URL Slug from Title";

$slug = slug($string);

echo $slug;


Output Is:

Comments: (Your feedback is valuable to us)

Michael Hamilton 1 year ago Reply

Which script editor is used in the displays of code ?