You could create a few explanatory local variables:
$lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/'; $spacesAndDuplicateHyphens = '/[\-\s]+/';
Usage:
$lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/';
$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug));
$spacesAndDuplicateHyphens = '/[\-\s]+/';
$slug = preg_replace($spacesAndDuplicateHyphens, '-', $slug);
These would eliminate the comments. (I haven't checked the regexps, other names might be more appropriate.)
Reference: Chapter 6. Composing Methods, Introduce Explaining Variable in Refactoring: Improving the Design of Existing Code by Martin Fowler:
Put the result of the expression, or parts of the expression, in a temporary variable with a name that explains the purpose.
And Clean Code by Robert C. Martin, G19: Use Explanatory Variables.
slug
could be renamed tocleanSlug
(contains a verb) to describe what the function does.I'd rename the
$string
variable to$slug
It would be more descriptive, it would express the intent of the variable.I'd use a whitelist instead of the blacklist. Defining the allowed characters (A-Z, 0-9 etc) would create proper URLs from URLs which contain special characters like
é
orű
.