PHP

Generate SEO-Friendly URL Slugs from Strings

Convert any string into a clean, SEO-friendly URL slug (e.g., for blog posts or product names) using a series of regular expression replacements in PHP.

<?php
function generateSlug($string) {
    // Convert to lowercase
    $slug = strtolower($string);

    // Replace non-alphanumeric characters with hyphens, except spaces
    $slug = preg_replace('/[^a-z0-9\s-]/', '', $slug);

    // Replace spaces with hyphens
    $slug = preg_replace('/\s+/', '-', $slug);

    // Remove multiple consecutive hyphens
    $slug = preg_replace('/-+/', '-', $slug);

    // Trim hyphens from start and end
    $slug = trim($slug, '-');

    return $slug;
}

echo generateSlug("My Awesome Blog Post Title!"); // Output: my-awesome-blog-post-title
echo "
";
echo generateSlug("Another_post with -- weird characters & numbers 123"); // Output: another-post-with-weird-characters-numbers-123
echo "
";
echo generateSlug("   Product Name with  Lots of   Spaces   "); // Output: product-name-with-lots-of-spaces
?>
How it works: This PHP function, `generateSlug`, converts a given string into an SEO-friendly URL slug. It first converts the string to lowercase. Then, it uses `preg_replace` with several regex patterns: to remove non-alphanumeric characters (keeping spaces and hyphens), to replace spaces with single hyphens, and to condense multiple hyphens into a single one. Finally, `trim` removes any leading or trailing hyphens, resulting in a clean, web-safe slug.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs