Skip to content
d3n.blog
Go back

A PHP Slugify Function with UTF-8 Support for Latin, Arabic, Chinese and More

A short PHP function that turns any UTF-8 string, in Latin, Arabic, Chinese or other scripts, into a URL slug, with an optional length limit.

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


Follow new posts by RSS