Slugify a string in PHP
Create URL-safe lowercase slugs from titles, removing accents and punctuation.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?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
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.
Related snippets
- Python Tested
Slugify a string
Turn text into a lowercase, hyphenated, ASCII-only slug using only the standard library.
- JavaScript Tested
Slugify a string for URLs
Convert any title into a lowercase, hyphenated, accent-free slug that is safe to use in a URL.
- HTML
Essential head tags for SEO and sharing
The meta, canonical, Open Graph and icon tags every public page should have.
- JavaScript Tested
Truncate a string with an ellipsis
Shorten text to a maximum length without cutting in the middle of a word or a Unicode character.

