<?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
Create a free account and build your private vault. Share publicly whenever you want.