Back to Top


1397/03/25 - 00:12

Laravel Seo Slug function - for seo purpose- utf8 and asccii support

Today, I wanna explain how we can show url slug in laravel for seo

کلمات کلیدی

LaravelSeoSlugUrl

Laravel Seo Slug function - for seo purpose- utf8 and asccii support
I used from Codeigniter (url_title) method that get a string and seprate it's word with a separator and return new string.


public static function generateSlug($str, $separator = '-', $lowercase = FALSE)
{
    if ($separator === 'dash') {
        $separator = '-';
    } elseif ($separator === 'underscore') {
        $separator = '_';
    }

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

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

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

    if ($lowercase === TRUE) {
        $str = strtolower($str);
    }

    return trim(trim($str, $separator));

}