Tuesday 2 June 2015

PHP: Clean URL

<?php

function cleanURL($string)
{
    $url = str_replace("'", '', $string);    $url = str_replace('%20', ' ', $url);
    $url = preg_replace('~[^\\pL0-9_]+~u', '-', $url); // substitutes anything but letters, numbers and '_' with separator
    $url = trim($url, "-");
    $url = iconv("utf-8", "us-ascii//TRANSLIT", $url);  // you may opt for your own custom character map for encoding.
    $url = strtolower($url);
    $url = preg_replace('~[^-a-z0-9_]+~', '', $url); // keep only letters, numbers, '_' and separator
    return $url;
}

// echo cleanURL("Shelly's%20Greatest%20Poem%20(2008)");  // shellys-greatest-poem-2008

?>
 

Usage


Useful for blog posts for instance, where a title can be something like
"It's over 100 degrees today!"
which would translate to

"its-over-100-degrees-today". So you can store the string and call it like http://examplesite.com/news/2008/its-over-100-degrees-today

$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url); // substitutes anything but letters, numbers and '_' with separator
That line removed all LETTERS from my links... which aint good, i like letters.

0 comments:

Post a Comment