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:
- First of all we remove any characters which are not a letter from the alphabet, a number or a special character (/,_, etc).
- Next we trimmed the string and lower the characters.
- Finally we replace character like +,[,_ with a -.
Let’s see step by step what this function is doing this string: I’m # an example !
- Im an example
- im-an-example
- not even needed
No comments:
Post a Comment