Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to turn a string into a URL slug

Short answer

Lowercase the string, replace everything except letters and digits with a hyphen and trim the hyphens at the ends:

<?php
 
function slug(string $text): string
{
    $text = strtolower($text);
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
 
    return trim($text, '-');
}
 
echo slug('Hello, World! PHP 8.4');

Output:

hello-world-php-8-4

Non-ASCII text

Non-ASCII letters are replaced with ASCII ones first. The intl extension does that; without it, build a replacement table for strtr():

<?php
 
$map = ['п' => 'p', 'р' => 'r', 'и' => 'i', 'в' => 'v', 'е' => 'e', 'т' => 't'];
 
echo strtr('привет', $map);

Output:

privet

Functions used in this recipe

  • preg_replace — Replaces everything that matches a regular expression.
  • strtolower — Converts ASCII letters to lowercase.
  • trim — Removes whitespace and other characters from both ends of a string.

Thanks for reading!

Donate to the site — we work hard for you.