Skip to content
Recommend our themes and earn 30% of our share of every sale you bring. Free to join.Earn by recommending our themes Become an affiliate

How to create slug in PHP?

Updated 20 Jun 2018
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;
    }
?>

More code answers

Comments

Log in to leave a comment.