Just a slug generator. I'm wondering if this can be simplified any further.
Many thanks.
<?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"
Updated version based on feedback:
<?php
function createSlug($slug) {
$lettersNumbersSpacesHyphens = '/[^\-\s\pN\pL]+/u';
$spacesDuplicateHypens = '/[\-\s]+/';
$slug = preg_replace($lettersNumbersSpacesHyphens, '', $slug);
$slug = preg_replace($spacesDuplicateHypens, '-', $slug);
$slug = trim($slug, '-');
return mb_strtolower($slug, 'UTF-8');
}
echo createSlug('-- This is an example ű of an ------ article - @@@ ..,.%&*£%$&*(*');
?>