Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP to convert string to slug

Tags:

string

php

What is the best way to convert a string of text to a slug? Meaning:

  • alpha allowed, convert to lowercase
  • numbers are allowed
  • spaces should be eliminated, not converted to dash ("-")
  • accented characters replaced by equivalent standard alpha
  • no other characters allowed, should be stripped out

I have found plenty of code online, but it all tends to convert spaces to dashes, which I do not want to do.

I am also interested optionally in varying the conversion, wherein:

  • ampersand ("&") should be replaced by the string "and"

And also a variant wherein:

  • Don't bother converting accented characters to equivalent standard alpha
like image 732
Robert Andrews Avatar asked Nov 16 '16 20:11

Robert Andrews


1 Answers

Previous one is good solution. But unfortunately it cuts off specific letters like ć or ż. If you want to keep them, then:

public static function createSlug($str, $delimiter = '-'){

    $unwanted_array = ['ś'=>'s', 'ą' => 'a', 'ć' => 'c', 'ç' => 'c', 'ę' => 'e', 'ł' => 'l', 'ń' => 'n', 'ó' => 'o', 'ź' => 'z', 'ż' => 'z',
        'Ś'=>'s', 'Ą' => 'a', 'Ć' => 'c', 'Ç' => 'c', 'Ę' => 'e', 'Ł' => 'l', 'Ń' => 'n', 'Ó' => 'o', 'Ź' => 'z', 'Ż' => 'z']; // Polish letters for example
    $str = strtr( $str, $unwanted_array );

    $slug = strtolower(trim(preg_replace('/[\s-]+/', $delimiter, preg_replace('/[^A-Za-z0-9-]+/', $delimiter, preg_replace('/[&]/', 'and', preg_replace('/[\']/', '', iconv('UTF-8', 'ASCII//TRANSLIT', $str))))), $delimiter));
    return $slug;
}
like image 176
Amir Djaminov Avatar answered Sep 23 '22 04:09

Amir Djaminov