Skip to main content

The problem with titles of your articles is that they are not URL friendly. They can contain spaces, UTF-8 characters and other stuff that will break the functionality of your web site.

<?php

/**
 * Generate URL friendly title
 *
 * The problem with titles of your articles is that they are not URL friendly.
 * They can contain spaces, UTF-8 characters and other stuff that will break
 * the functionality of your web site.
 *
 * And you want the title of the article to be in your URL because it is so much
 * SEO and human friendlier. As I often develop sites in this way, here is a small
 * but handy function that you can include in your code and call whenever you
 * need to generate URL friendly text.
 *
 * As I am often dealing with files, this function has an optional parameter
 * called $dot which tells us whether to leave the dot inside the text
 * (files needs that the dot is not removed) or not.
 *
 * @link http://www.codeforest.net/how-to-generate-url-friendly-title
 *
 * @param string $string
 * @param string $space
 * @param string $dot
 * @return string
 */
function generateSlug ($string, $space = "-", $dot = null)
{
    if (function_exists('iconv')) {
        $string = @iconv('UTF-8', 'ASCII//TRANSLIT', $string);
    }

    if (! $dot) {
        $string = preg_replace("/[^a-zA-Z0-9 -]/", "", $string);
    } else {
        $string = preg_replace("/[^a-zA-Z0-9 -.]/", "", $string);
    }

    $string = trim(preg_replace("/s+/", " ", $string));
    $string = strtolower($string);
    $string = str_replace(" ", $space, $string);

    return $string;
}

?>