From the archive: first published in February 2017 on my old blog, Tux86’s Web Tech Blog. Versions, links and screenshots are from that time.
Here is a small “magic” PHP function that slugifies a UTF-8 string, whether it is written in Latin, Arabic, Chinese or another script:
<?php
function slug($str, $limit = null) {
if ($limit) {
$str = mb_substr($str, 0, $limit, "utf-8");
}
$text = html_entity_decode($str, ENT_QUOTES, 'UTF-8');
// replace non letter or digits by -
$text = preg_replace('~[^\\pL\d]+~u', '-', $text);
// trim
$text = trim($text, '-');
return $text;
}