Skip to content
GreenSnippets

Slugify a string in PHP

Create URL-safe lowercase slugs from titles, removing accents and punctuation.

PHP
<?php
function slugify(string $text, int $maxLength = 80): string
{
    if (class_exists('Transliterator')) {
        $text = Transliterator::create('Any-Latin; Latin-ASCII; Lower()')->transliterate($text);
    } else {
        $text = strtolower((string) iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $text));
    }
    $text = trim((string) preg_replace('/[^a-z0-9]+/', '-', $text), '-');
    return rtrim(substr($text, 0, $maxLength), '-');
}

Example / expected output

Output
slugify('Hello, World! 2025'); // "hello-world-2025"

How it works

iconv with //TRANSLIT converts accents to ASCII where the platform supports it. When intl is installed, Transliterator is more reliable across systems. Everything that is not a letter or digit collapses to a single hyphen.