Skip to main content
2 of 5
Please don't add "thanks" - show them with upvotes
Jamal
  • 34.9k
  • 13
  • 133
  • 237

Slug URL Generator

Just a slug generator. I'm wondering if this can be simplified any further.

<?php
function slug($string) {

    // Replace all non letters, numbers, spaces or hypens
    $string = preg_replace('/[^\-\sa-zA-Z0-9]+/', '', mb_strtolower($string));

    // Replace spaces and duplicate hyphens with a single hypen
    $string = preg_replace('/[\-\s]+/', '-', $string);

    // Trim off left and right hypens
    $string = trim($string, '-');

    return $string;
}

echo slug('-- This is an example     of an ------ article   - @@@ ..,.:~&**%$£%$^*'); // outputs "this-is-an-example-of-an-article"