PHP Code Examples

Create a URL Slug from a Title in PHP

Convert a simple title into a URL-friendly slug and explain the limits of basic ASCII transliteration.

Example

<?php
function createSlug(string $title): string
{
    $title = strtolower(trim($title));
    $title = preg_replace('/[^a-z0-9]+/', '-', $title) ?? '';
    return trim($title, '-');
}

echo createSlug('PHP Code Examples: A Practical Guide');
// php-code-examples-a-practical-guide

Unicode titles

The simple example intentionally keeps ASCII letters and digits. For multilingual websites, use the intl extension's transliteration support or a well-tested slug library so characters from languages such as Turkish are handled consistently.

Database advice

Add a unique index to the slug column and resolve collisions before saving. Never assume that two different titles will produce different slugs.

Share this page Help other developers discover this resource.