Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a string to alphanumeric and convert spaces to dashes? [closed]

Tags:

php

I'd like to take a string, strip it of all non-alphanumeric characters and convert all spaces into dashes.

like image 794
Decoy Avatar asked Jan 08 '12 03:01

Decoy


2 Answers

I use the following code whenever I want to convert headlines or other strings to URL slugs. It does everything you ask for by using RegEx to convert any string to alphanumeric characters and hyphens.

function generateSlugFrom($string)
{
    // Put any language specific filters here, 
    // like, for example, turning the Swedish letter "å" into "a"

    // Remove any character that is not alphanumeric, white-space, or a hyphen 
    $string = preg_replace('/[^a-z0-9\s\-]/i', '', $string);
    // Replace all spaces with hyphens
    $string = preg_replace('/\s/', '-', $string);
    // Replace multiple hyphens with a single hyphen
    $string = preg_replace('/\-\-+/', '-', $string);
    // Remove leading and trailing hyphens, and then lowercase the URL
    $string = strtolower(trim($string, '-'));

    return $string;
}

If you are going to use the code for generating URL slugs, then you might want to consider adding a little extra code to cut it after 80 characters or so.

if (strlen($string) > 80) {
    $string = substr($string, 0, 80);

    /**
     * If there is a hyphen reasonably close to the end of the slug,
     * cut the string right before the hyphen.
     */
    if (strpos(substr($string, -20), '-') !== false) {
        $string = substr($string, 0, strrpos($string, '-'));
    }
}
like image 75
Tom Avatar answered Nov 01 '22 08:11

Tom


Ah, I have used this before for blog posts (for the url).

Code:

$string = preg_replace("/[^0-9a-zA-Z ]/m", "", $string);
$string = preg_replace("/ /", "-", $string);

$string will contain the filtered text. You can echo it or do whatever you want with it.

like image 34
blake305 Avatar answered Nov 01 '22 07:11

blake305