Neuron-PHP

SlugGenerator
in package

Slug Generator Service

Generates URL-safe slugs from text strings. Used across the CMS for creating SEO-friendly URLs for posts, pages, events, categories, and tags.

Handles:

  • Converting text to lowercase
  • Replacing non-alphanumeric characters with hyphens
  • Removing consecutive hyphens
  • Trimming hyphens from start/end
  • Fallback for non-ASCII text (e.g., Chinese, Arabic)

Table of Contents

Methods

clean()  : string
Clean an existing slug (useful for user-provided slugs)
generate()  : string
Generate a URL-safe slug from a string
generateUnique()  : string
Generate a slug with uniqueness check via callback
isValid()  : bool
Validate if a string is a valid slug format

Methods

clean()

Clean an existing slug (useful for user-provided slugs)

public clean(string $slug[, string $fallbackPrefix = 'item' ]) : string
Parameters
$slug : string

The slug to clean

$fallbackPrefix : string = 'item'

Prefix for fallback if slug becomes empty after cleaning

Return values
string

The cleaned slug

generate()

Generate a URL-safe slug from a string

public generate(string $text[, string $fallbackPrefix = 'item' ]) : string
Parameters
$text : string

The text to convert to a slug

$fallbackPrefix : string = 'item'

Prefix for fallback slug when no ASCII characters (default: 'item')

Return values
string

The generated slug

generateUnique()

Generate a slug with uniqueness check via callback

public generateUnique(string $text, callable $existsCallback[, string $fallbackPrefix = 'item' ]) : string

If the generated slug already exists, appends a number suffix to make it unique (e.g., "my-post", "my-post-2", "my-post-3")

Parameters
$text : string

The text to convert to a slug

$existsCallback : callable

Callback to check if slug exists: fn(string $slug): bool

$fallbackPrefix : string = 'item'

Prefix for fallback slug when no ASCII characters

Return values
string

A unique slug

isValid()

Validate if a string is a valid slug format

public isValid(string $slug) : bool

Valid slugs contain only lowercase letters, numbers, and hyphens. They cannot start or end with a hyphen.

Parameters
$slug : string

The slug to validate

Return values
bool

True if valid, false otherwise


        
On this page

Search results