How to make SEO friendly URLs from any string with PHP?

I wanted to convert very complicated strings in to SEO friendly URLs. The challenge was to generate a unified URL after removing all illegal characters in the string.

As I roam through internet I could find the following cool function which returns a nice URL no matter what we through at it. I modified the function a little bit.

setlocale(LC_ALL, 'en_US.UTF8'); //Set locale to English for all of the below

function BuildUrl($str, $delimiter='-', $replace=array()) {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
$clean = strtolower(trim($clean, '-'));
$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

return $clean;
}

Just call the function with your string as it’s parameter.

       
            $clean_url=BuildUrl($string);


Optional Settings

By default all the spaces and illegal blocks will be separated by a hyphen (-) but if you prefer to use a different character just define your character in the second parameter.

Eg. this-is-my-clean-url vs this_is_my_clean_url

           $clean_url=BuildUrl($string, "_");

In an advance situation if your string contains some characters which should be converted to a legal character or character set rather than removing them from the URL define your if then list as an array like below and define it as the third parameter.

   $replace = array(
'illegal' => array('/ä/', '/ö/', '/ü/', '/Â/', '/é/'),
'legal' => array('ae', 'oe', 'ue', 'Aa', 'e')
);

$clean_url=BuildUrl($string, "_", $replace);

Hope this will be helpful to your situation :).

Cheers!

Like this post? Please share to your friends:
Leave a Reply

;-) :| :x :twisted: :smile: :shock: :sad: :roll: :razz: :oops: :o :mrgreen: :lol: :idea: :grin: :evil: :cry: :cool: :arrow: :???: :?: :!: