PHP function to make slug (URL string) PHP function to make slug (URL string) php php

PHP function to make slug (URL string)


Instead of a lengthy replace, try this one:

public static function slugify($text, string $divider = '-'){  // replace non letter or digits by divider  $text = preg_replace('~[^\pL\d]+~u', $divider, $text);  // transliterate  $text = iconv('utf-8', 'us-ascii//TRANSLIT', $text);  // remove unwanted characters  $text = preg_replace('~[^-\w]+~', '', $text);  // trim  $text = trim($text, $divider);  // remove duplicate divider  $text = preg_replace('~-+~', $divider, $text);  // lowercase  $text = strtolower($text);  if (empty($text)) {    return 'n-a';  }  return $text;}

This was based off the one in Symfony's Jobeet tutorial.


Update

Since this answer is getting some attention, I'm adding some explanation.

The solution provided will essentially replace everything except A-Z, a-z, 0-9, & - (hyphen) with - (hyphen). So, it won't work properly with other unicode characters (which are valid characters for a URL slug/string). A common scenario is when the input string contains non-English characters.

Only use this solution if you're confident that the input string won't have unicode characters which you might want to be a part of output/slug.

Eg. "नारी शक्ति" will become "----------" (all hyphens) instead of "नारी-शक्ति" (valid URL slug).

Original Answer

How about...

$slug = strtolower(trim(preg_replace('/[^A-Za-z0-9-]+/', '-', $string)));

?


If you have intl extension installed, you can use Transliterator::transliterate function to create a slug easily.

<?php$string = 'Namnet på bildtävlingen';$slug = \Transliterator::createFromRules(    ':: Any-Latin;'    . ':: NFD;'    . ':: [:Nonspacing Mark:] Remove;'    . ':: NFC;'    . ':: [:Punctuation:] Remove;'    . ':: Lower();'    . '[:Separator:] > \'-\'')    ->transliterate( $string );echo $slug; // namnet-pa-bildtavlingen?>