PHP: How to Convert a Title to a Slug

Updated: January 10, 2024 By: Guest Contributor Post a comment

Introduction

Creating slugs from titles in PHP is a common task required when building URLs that are both user and search engine friendly. In this tutorial, we will explore several methods of converting titles to slugs, progressing from basic string manipulation to more advanced techniques.

Understanding Slugs

In the context of web development, a slug is the part of a URL that identifies a particular page on a website in an easy-to-read form. It is typically generated from a page title and is included in the URL structure. A good slug is short, meaningful, and contains only lower-case letters, numbers, and hyphens.

Simple Slug Generation with str_replace()

One of the most basic ways to create a slug in PHP is by using the str_replace() function. The goal is to replace all spaces with hyphens and convert the string to lower case.

<?php
$title = "Example Title for Conversion";
$slug = str_replace(' ', '-', strtolower($title));
echo $slug; // Outputs: example-title-for-conversion
?>

Using preg_replace() for Advanced Replacement

While str_replace() is good for simple space-to-hyphen conversions, it doesn’t handle non-alphanumeric characters or multiple consecutive spaces. To address this, we can use preg_replace() to create a more versatile slug conversion function.

<?php
function createSlug($title) {
    // Convert to lower case
    $title = strtolower($title);
    // Replace spaces with hyphens
    $title = preg_replace('/\s+/', '-', $title);
    // Remove non-alphanumeric characters except hyphens
    $title = preg_replace('/[^a-z0-9-]/', '', $title);
    // Remove multiple consecutive hyphens
    $title = preg_replace('/-+/', '-', $title);
    // Trim hyphens from the beginning and end
    $title = trim($title, '-');
    return $title;
}
$exampleTitle = "This -- is a #test!";
echo createSlug($exampleTitle); // Outputs: this-is-a-test
?>

Incorporating Unicode Characters with iconv()

When dealing with titles containing accented or special characters, a standard approach might not suffice. The iconv() function can be used to transliterate these characters to their ASCII equivalents before slugification.

<?php
function createSlug($title) {
    // Transliterate unicode characters to ASCII
    $title = iconv('UTF-8', 'ASCII//TRANSLIT', $title);
    // Continue with previous preg_replace() calls
    // ...
}
$exampleTitle = "Café au lait & croissants";
echo createSlug($exampleTitle); // Outputs: cafe-au-lait-croissants
?>

Handling Multibyte Characters with mb_ Functions

If iconv() doesn’t handle certain characters well or is not available on your server, you can use PHP’s multibyte string functions, such as mb_strtolower(), to ensure proper case conversion for characters beyond the ASCII range.

<?php
// Include previous createSlug() logic here...
function createSlug($title) {
    // Convert to lower case while respecting multibyte characters
    $title = mb_strtolower($title, 'UTF-8');
    // ...
}
// Rest of the code...
?>

Combining Techniques with PHP Frameworks

Modern PHP frameworks like Laravel come with built-in string manipulation functions that handle slug creation elegantly. For instance, Laravel’s Str::slug() method internally uses multiple functions to ensure a clean and standardized slug.

use Illuminate\Support\Str;
// ...
$exampleTitle = "New Laravel 8 Features";
$slug = Str::slug($exampleTitle);
echo $slug; // Outputs: new-laravel-8-features

Final Touches: Validating and Ensuring Uniqueness

While generating slugs, validation and uniqueness are important. Slugs are often used as keys in a database, so they must be unique. PHP frameworks typically handle this by appending a count or unique identifier if a duplicate is detected.

// Sample Laravel code showing slug uniqueness by appending an ID
$slugBase = Str::slug($exampleTitle);
$count = 1;
while (Model::where('slug', '=', $slug)->exists()) {
    $slug = $slugBase . '-' . $count;
    $count++;
}

Conclusion

To convert a title to a slug in PHP, it is essential to understand the different techniques according to your needs. Starting from basic string functions and advancing to internationalization and framework-specific features, you can tailor slug conversion to any scenario. Ensuring both readability and uniqueness will help maintain effective user experience and SEO optimization for your web applications.