php slugify function

Solutions on MaxInterview for php slugify function by the best coders in the world

showing results for - "php slugify function"
Emma
11 Jul 2016
1function slugify($string, $replace = array(), $delimiter = '_')
2{
3    // https://github.com/phalcon/incubator/blob/master/Library/Phalcon/Utils/Slug.php
4    if (!extension_loaded('iconv')) {
5        throw new Exception('iconv module not loaded');
6    }
7    // Save the old locale and set the new locale to UTF-8
8    $oldLocale = setlocale(LC_ALL, '0');
9    setlocale(LC_ALL, 'en_US.UTF-8');
10    $clean = iconv('UTF-8', 'ASCII//TRANSLIT', $string);
11    if (!empty($replace)) {
12        $clean = str_replace((array) $replace, ' ', $clean);
13    }
14    $clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
15    $clean = strtolower($clean);
16    $clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);
17    $clean = trim($clean, $delimiter);
18    // Revert back to the old locale
19    setlocale(LC_ALL, $oldLocale);
20    return $clean;
21}
22
23echo slugify('àa kasdlnmkl asld amlks o+s df<+ùpsfjovù+p<sjrfàp');
24// returns: aa_kasdlnmkl_asld_amlks_o_s_df_upsfjovu_psjrfap
Aarón
14 Feb 2020
1public static function slugify($text, string $divider = '-')
2{
3  // replace non letter or digits by divider
4  $text = preg_replace('~[^\pL\d]+~u', $divider, $text);
5
6  // transliterate
7  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);
8
9  // remove unwanted characters
10  $text = preg_replace('~[^-\w]+~', '', $text);
11
12  // trim
13  $text = trim($text, $divider);
14
15  // remove duplicate divider
16  $text = preg_replace('~-+~', $divider, $text);
17
18  // lowercase
19  $text = strtolower($text);
20
21  if (empty($text)) {
22    return 'n-a';
23  }
24
25  return $text;
26}
27