PHP to convert string to slug

What is the best way to convert a string of text to a pool? Value:

  • alpha allowed, convert to lowercase
  • numbers allowed
  • spaces should be removed, not converted to dashes ("-")
  • accented characters are replaced by the equivalent alpha standard
  • no other characters are allowed, must be removed

I found a lot of code on the Internet, but all of this tends to convert spaces to dashes, which I don't want to do.

I'm also interested in the ability to change conversions, where:

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

And also an option in which:

  • Don't bother converting accented characters to equivalent standard alpha
+5
2

, (http://cubiq.org/the-perfect-php-clean-url-generator). '' , '-'.

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

    $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;

} 
+12

- . , , , ć ż. , :

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;
}
+1

Source: https://habr.com/ru/post/1660993/


All Articles