Create URL slugs from UTF-8 titles
PHP
<?php
declare(strict_types=1);
/** Turn a UTF-8 title into a lowercase ASCII slug suitable for URLs. */
function slugify(string $title, int $maxLength = 60): string
{
if (function_exists('iconv')) {
$ascii = @iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $title);
if ($ascii !== false) {
// Some iconv builds mark accents with ASCII symbols; drop those marks.
$title = preg_replace('/[\x60\'"^~]+/', '', $ascii) ?? $ascii;
}
}
$slug = preg_replace('/[^a-z0-9]+/', '-', strtolower($title)) ?? '';
$slug = trim($slug, '-');
if ($slug === '') {
return 'untitled';
}
$slug = substr($slug, 0, $maxLength);
return rtrim($slug, '-');
}
$titles = ['Hello, World!', 'Crème brûlée & café', ' -- Already A Slug -- ', '???'];
foreach ($titles as $title) {
echo slugify($title), PHP_EOL;
}