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
If you are interested in writing for Hyvor Developer, please let us know via email: [email protected]
Latest on Hyvor Developer
Image for Creating a Real-Time Chat App with PHP and Node.js
Creating a Real-Time Chat App with PHP and Node.js
Image for All About MYSQLI Prepared Statements in PHP
All About MYSQLI Prepared Statements in PHP
Image for Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image Upload with AJAX, PHP, and MYSQL - The Beginner's Guide
Image for PHP Contact Form - The Email Method
PHP Contact Form - The Email Method
Related Articles
0