php 39 lines · 8 steps

Building a URL slug from any title in PHP

A step-by-step regex pipeline turns arbitrary, accented text into a clean, lowercase URL slug.

Explained by highlit
1<?php
2 
3namespace App\Support;
4 
5final class Slugifier
6{
7 public function make(string $title, string $separator = '-'): string
8 {
9 $title = $this->transliterate($title);
10 $title = mb_strtolower($title, 'UTF-8');
11 
12 $flip = $separator === '-' ? '_' : '-';
13 $title = preg_replace('![' . preg_quote($flip, '!') . ']+!u', $separator, $title);
14 
15 $title = str_replace('@', $separator . 'at' . $separator, $title);
16 
17 $title = preg_replace('![^' . preg_quote($separator, '!') . '\pL\pN\s]+!u', '', $title);
18 
19 $title = preg_replace('![' . preg_quote($separator, '!') . '\s]+!u', $separator, $title);
20 
21 return trim($title, $separator);
22 }
23 
24 private function transliterate(string $value): string
25 {
26 if (function_exists('transliterator_transliterate')) {
27 $transliterated = transliterator_transliterate(
28 'Any-Latin; Latin-ASCII; [\u0080-\u7fff] remove',
29 $value
30 );
31 
32 if ($transliterated !== false) {
33 return $transliterated;
34 }
35 }
36 
37 return iconv('UTF-8', 'ASCII//TRANSLIT//IGNORE', $value) ?: $value;
38 }
39}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Normalizing accents to ASCII before slugifying keeps URLs stable across languages.
  2. 2Layering small regex passes — flip, strip, collapse, trim — is clearer than one monster pattern.
  3. 3Preferring the intl extension with an iconv fallback makes transliteration robust across environments.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Building a URL slug from any title in PHP — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code