What is the best way to convert a string of text to a slug? Meaning:
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:
And also a variant wherein:
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With