Documentation

SlugGenerator
in package

SlugGenerator - Reusable Slug Generation Helper

Provides utility methods to generate URL-friendly slugs from strings. Handles accent removal, special character sanitization, and slug uniqueness.

Usage:

$slug = SlugGenerator::generate('Mon Premier Article');
// Returns: "mon-premier-article"

$uniqueSlug = SlugGenerator::generateUnique('Mon Article', function($slug) {
    // Check if slug exists in database
    return $this->slugExists($slug);
Tags
version
1.0.0
author

BdeLive - Group 8

Table of Contents

Methods

generate()  : string
Generate a URL-friendly slug from a string
generateUnique()  : string
Generate a unique slug from a string
isValid()  : bool
Validate if a string is a valid slug format
removeAccents()  : string
Remove accents from a string

Methods

generate()

Generate a URL-friendly slug from a string

public static generate(string $string) : string

Converts a string to lowercase, replaces spaces and special characters with hyphens, removes accents, and ensures the slug is URL-safe.

Examples:

  • "Mon Premier Article" → "mon-premier-article"
  • "Événement Spécial!" → "evenement-special"
  • "Article avec espaces" → "article-avec-espaces"
Parameters
$string : string

The string to convert

Return values
string

The generated slug

generateUnique()

Generate a unique slug from a string

public static generateUnique(string $string, callable $existsCallback) : string

If a slug already exists (according to the provided callback), appends a number to make it unique. Example: "mon-article", "mon-article-2", "mon-article-3"

Parameters
$string : string

The string to convert

$existsCallback : callable

Callback function that checks if slug exists. Returns bool.

Return values
string

A unique slug

isValid()

Validate if a string is a valid slug format

public static isValid(string $slug) : bool

A valid slug contains only lowercase letters, numbers, and hyphens. It should not start or end with a hyphen.

Parameters
$slug : string

The slug to validate

Return values
bool

True if valid, false otherwise

removeAccents()

Remove accents from a string

private static removeAccents(string $string) : string

Converts accented characters to their non-accented equivalents. Examples: é→e, à→a, ç→c, ñ→n

Parameters
$string : string

The string to process

Return values
string

The string without accents


        
On this page

Search results