Sunday, August 19, 2012

How to clean URL in PHP



Have nice and clean URL on your website is mandatory to provide a better visibility on search engines. Let’s say you want a URL like that: http://www.florian-hacquebart.eu/news/161/clean-url-in-php you will have to use URL rewriting which is not the first subject of this post but for instance you will have to generate a specific string: clean-url-in-php instead of Clean URL in PHP.

You can do that by using regulars expressions:


function cleanURL($title) {
$title = preg_replace("/[^a-zA-Z0-9/_|+ -]/", '', $title);
$title = strtolower(trim($title, '-'));
$title = preg_replace("/[/_|+ -]+/", '-', $title);

return $title;
}



What are we doing in this function:

  1. First of all we remove any characters which are not a letter from the alphabet, a number or a special character (/,_, etc).

  2. Next we trimmed the string and lower the characters.

  3. Finally we replace character like +,[,_ with a -.


Let’s see step by step what this function is doing this string: I’m # an example !

  1. Im an example

  2. im-an-example

  3. not even needed



 

 

No comments:

Post a Comment