2

Possible Duplicate:
URL Friendly Username in PHP?

Is there a way to make strings "URL safe" which means replacing whitespaces with hyphens, removing any punctuation and change all capital letters to lowercase?

For example:

"This is a STRING" -› "this-is-a-string"

or

"Hello World!" –› "hello-world"
Community
  • 1
  • 1
user1706680
  • 1,103
  • 3
  • 15
  • 34

2 Answers2

9

You can use preg_replace to replace change those characters.

$safe = preg_replace('/^-+|-+$/', '', strtolower(preg_replace('/[^a-zA-Z0-9]+/', '-', $string)));
kmkaplan
  • 18,655
  • 4
  • 51
  • 65
2

I Often use this function to generate my clean urls and seems to work fine, You could alter it according to your needs but give it a try.

function sanitize($string, $force_lowercase = true, $anal = false) {
    $strip = array("~", "`", "!", "@", "#", "$", "%", "^", "&", "*", "(", ")", "_", "=", "+", "[", "{", "]",
                   "}", "\\", "|", ";", ":", "\"", "'", "‘", "’", "“", "”", "–", "—",
                   "—", "–", ",", "<", ".", ">", "/", "?");
    $clean = trim(str_replace($strip, "", strip_tags($string)));
    $clean = preg_replace('/\s+/', "-", $clean);
    $clean = ($anal) ? preg_replace("/[^a-zA-Z0-9]/", "", $clean) : $clean ;
    return ($force_lowercase) ?
        (function_exists('mb_strtolower')) ?
            mb_strtolower($clean, 'UTF-8') :
            strtolower($clean) :
        $clean;
}
0x_Anakin
  • 3,229
  • 5
  • 47
  • 86