How to create SEO friendly slug URL in PHP

When you are using CORE PHP to create blog type website than this tutorial is really helpful. We will write SEO friendly URL like WordPress blog. That remove all spaces, special characters etc..

Create slug.php file

<code data-enlighter-language="php" class="EnlighterJSRAW">function display_name_slug($string, $wordLimit = 30){
    $separator = '-';
    
    if($wordLimit != 0){
        $wordArr = explode(' ', $string);
        $string = implode(' ', array_slice($wordArr, 0, $wordLimit));
    }

    $quoteSeparator = preg_quote($separator, '#');

    $trans = array(
        '&.+?;'                 	=> '',
        '[^\w\d _-]' 				=> '',
        '\s+'                   	=> $separator,
        '('.$quoteSeparator.')+'	=> $separator
    );

    $string = strip_tags($string);
    foreach ($trans as $key => $val){
        $string = preg_replace('#'.$key.'#i'.('UTF8_ENABLED' ? 'u' : ''), $val, $string);
    }

    $string = strtolower($string);

    return trim(trim($string, $separator));
}

You can call this function display_name_slug($string=’pass any string here’, $wordLimit = 30) you can choose any limit of string to return, for now I mention 30

Comments

No comments yet. Why don’t you start the discussion?

    Leave a Reply