Skip to content
Walid Karray
Go back

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

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

Share this post:

Follow new posts by RSS

Previous Post
Configuring a custom domain for AWS Lambda Function URLs
Next Post
Facebook Graph API Workaround: Get a Group's ID from Its URL