HiveBrain v1.2.0
Get Started
← Back to all entries
patternphpMinor

Slug URL Generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
slugurlgenerator

Problem

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:

Solution

-
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 to cleanSlug (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 ű.

Code Snippets

$lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/';
$spacesAndDuplicateHyphens = '/[\-\s]+/';
$lettersNumbersSpacesHypens = '/[^\-\sa-zA-Z0-9]+/';
$slug = preg_replace($lettersNumbersSpacesHypens, '', mb_strtolower($slug));

$spacesAndDuplicateHyphens = '/[\-\s]+/';
$slug = preg_replace($spacesAndDuplicateHyphens, '-', $slug);

Context

StackExchange Code Review Q#44335, answer score: 5

Revisions (0)

No revisions yet.