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($string$slug) {
// Replace all non letters, numbers, spaces or hypens
$lettersNumbersSpacesHyphens = preg_replace('/[^\-\s\pN\pL]+/u',u';
'', $string);
$spacesDuplicateHypens = '/[\-\s]+/ Replace';
spaces and duplicate hyphens$slug with= apreg_replace($lettersNumbersSpacesHyphens, single'', hypen$slug);
$spacesDuplicateHypens$slug = preg_replace('/[\-\s]+/'$spacesDuplicateHypens, '-', $lettersNumbersSpacesHyphens$slug);
// Trim off left and right hypens
$slug = trim($spacesDuplicateHypens$slug, '-');
return mb_strtolower($slug, 'UTF-8');
}
echo createSlug('-- This is an example ű of an ------ article - @@@ ..,.%&*£%$&*(*');
?>