How to create slug in PHP?


User friendly URLs are helpful for SEO as well as for users to know that what the webpage is about. So it is a good practice to create slugs for URLs. Below is a working function available to create slug from title.

Source Code:

<?php
    function slugify($slug) {
        $slug = preg_replace('~[^\pL\d]+~u', '-', $slug);
        $slug = iconv('utf-8', 'us-ascii//TRANSLIT', $slug);
        $slug = preg_replace('~[^-\w]+~', '', $slug);
        $slug = trim($slug, '-');
        $slug = preg_replace('~-+~', '-', $slug);
        $slug = strtolower($slug);
        if (empty($slug)) {
            return false;
        }
        return $slug;
    }
?>

Reviews and Comments