Strip php variable, replace white spaces with dashes

Php

Php Problem Overview


How can I convert a PHP variable from "My company & My Name" to "my-company-my-name"?

I need to make it all lowercase, remove all special characters and replace spaces with dashes.

Php Solutions


Solution 1 - Php

This function will create an SEO friendly string

function seoUrl($string) {
    //Lower case everything
    $string = strtolower($string);
    //Make alphanumeric (removes all other characters)
    $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
    //Clean up multiple dashes or whitespaces
    $string = preg_replace("/[\s-]+/", " ", $string);
    //Convert whitespaces and underscore to dash
    $string = preg_replace("/[\s_]/", "-", $string);
    return $string;
}

should be fine :)

Solution 2 - Php

Replacing specific characters: http://se.php.net/manual/en/function.str-replace.php

Example:

function replaceAll($text) { 
    $text = strtolower(htmlentities($text)); 
    $text = str_replace(get_html_translation_table(), "-", $text);
    $text = str_replace(" ", "-", $text);
    $text = preg_replace("/[-]+/i", "-", $text);
    return $text;
}

Solution 3 - Php

Yop, and if you want to handle any special characters you'll need to declare them in the pattern, otherwise they may get flushed out. You may do it that way:

strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $string)));

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRobView Question on Stackoverflow
Solution 1 - PhprorypickoView Answer on Stackoverflow
Solution 2 - PhpNoLifeKingView Answer on Stackoverflow
Solution 3 - PhpPierre VoisinView Answer on Stackoverflow