PHP

URL Slug Generator (UTF-8 safe)

admin by @admin ADMIN
Jun 20, 2026
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Convert any string into a clean URL-safe slug. Transliterates accented characters to ASCII, lowercases, replaces non-alphanumerics with dashes, and collapses runs of dashes. Works on UTF-8 input out of the box.
PHP
Raw
<?php
function slugify(string $text, string $sep = '-'): string {
    // Transliterate (é → e, ü → u, etc.) — requires the intl extension.
    if (function_exists('transliterator_transliterate')) {
        $text = transliterator_transliterate('Any-Latin; Latin-ASCII; Lower()', $text);
    } else {
        $text = strtolower($text);
    }
    $text = preg_replace('/[^a-z0-9]+/', $sep, $text);     // non-alnum → sep
    $text = trim($text, $sep);                              // strip outer seps
    $text = preg_replace('/' . preg_quote($sep, '/') . '{2,}/', $sep, $text);
    return $text;
}

echo slugify("Hello, World!");                  // hello-world
echo slugify("Café au lait — c'est délicieux"); // cafe-au-lait-c-est-delicieux
echo slugify("PHP 8.3 & Beyond");               // php-8-3-beyond
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.