How to Create SEO-Friendly Slugs in PHP

This page serves as a test to ensure that my PHP code correctly generates slugs from post titles. Previously, I created a slug but neglected to use hyphens (-) as separators, resulting in slugs like mysluglikethis instead of slug-work-like-this.

An SEO-friendly slug is important because it helps search engines understand your content by making the URL more descriptive and readable. While some frameworks automatically generate SEO-friendly slugs for you, if your system doesn’t, you can create them manually with PHP as demonstrated below.

Generating a Slug with PHP

Here’s a step-by-step guide to generating an SEO-friendly slug using PHP:

// Retrieve the title from the request
$judul = $this->request->getVar('judul');

// Convert the title to lowercase and trim whitespace from both ends
$title = trim(strtolower($judul));

// Replace spaces and special characters with hyphens
$title = preg_replace('/[^a-z0-9]+/', '-', $title);

// Remove any trailing hyphens
$title = trim($title, '-');

// Ensure the slug is not empty
$slug = !empty($title) ? $title : 'default-slug';

// Use $slug as needed, e.g., save it to your database

Explanation

  1. Retrieve and Clean the Title: The title is fetched and converted to lowercase while removing any leading or trailing whitespace.
  2. Replace Spaces and Special Characters: The preg_replace function replaces any sequence of non-alphanumeric characters with a single hyphen, ensuring a clean and readable slug.
  3. Remove Trailing Hyphens: Any trailing hyphens are removed to avoid unnecessary characters in the slug.
  4. Handle Empty Titles: If the resulting slug is empty, a default value is used to ensure that every post has a slug.

This approach will help you generate slugs that are more readable and SEO-friendly, improving the usability and search engine visibility of your content.

Feel free to adapt this code to fit your specific needs and ensure it aligns with the rest of your site’s functionality.

Share this post on :