PHP
Generate SEO-Friendly Slugs with PHP Regex
Learn to convert any string into an SEO-friendly URL slug (lowercase, hyphens instead of spaces/special chars) using a PHP regular expression.
<?php
function generateSlug(string $text): string
{
// Convert to lowercase
$text = strtolower($text);
// Replace non-alphanumeric characters (except hyphens) with hyphens
$text = preg_replace('/[^a-z0-9-]+/', '-', $text);
// Replace multiple hyphens with a single hyphen
$text = preg_replace('/-+/', '-', $text);
// Trim hyphens from start and end
$text = trim($text, '-');
return $text;
}
// Example usage:
// echo generateSlug("My Awesome Blog Post Title!"); // Output: my-awesome-blog-post-title
// echo generateSlug("Another_Example With Spaces & Symbols."); // Output: another-example-with-spaces-symbols
How it works: This PHP function `generateSlug` takes a string and transforms it into an SEO-friendly slug. It converts the text to lowercase, replaces non-alphanumeric characters (excluding hyphens) with single hyphens using `preg_replace`, removes any duplicate hyphens, and finally trims leading/trailing hyphens, resulting in a clean, URL-safe string.