How to Create a SEO-Friendly Slug from Title in PHP?


function getSlug($string) {
    // remove extra spaces
    $string = preg_replace('/\s+/', ' ', $string);
    
    // lowercase
    $string = strtolower($string);

    // remove non-latin
    $string = preg_replace("/[^a-z0-9\s]+/", '', $string); 

    $array = preg_split('/\s+/', $string);
    $array = array_filter($array, function($item) {
        // remove empty items
        return trim($item) !== "";
    });
    // get unique words
    $array = array_unique($array);
    
    // join
    $string = implode('-', $array);
    return $string;
}
Tagged: PHP
You can connect with me on Twitter or Linkedin.
Latest on My Blog
PHP Beginner's Tutorial
Beginner's PHP Tutorial
Image for Laravel High CPU Usage Because of File-based Session Storage
Laravel High CPU Usage Because of File-based Session Storage
Image for Resizing Droplets: A Personal Experience
Resizing Droplets: A Personal Experience
Image for Moving our CDN (10+ GB images) to a new server
Moving our CDN (10+ GB images) to a new server
Image for Disqus, the dark commenting system
Disqus, the dark commenting system
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Related Articles
4