Please wait...
Friendly URLs in PHP
When maintaining a website in this day and age, having well formatted URLs is a must for good SEO. Containing keywords in your URL helps search engines pick up your sites topic and niche. However when a URL is made for a page, it should always remain on that URL. Having multiple URLs for one page will do your site no good in terms of SEO.
So, when creating your URL for a page it would be a good idea to use a standard formatting rule. In PHP we can create a function to create this for us and always use it from then on.
URL's shouldnt contain special characters, so we should remove them from the URL we are creating. Lets start with making our function.
<?php function createURL( $string ) { }
In this function we will need an array of characters that we don't want in our URL. So lets create that.
$deleteChars = array(" ", "-", ".", ",", "&", "=", "+", "!", "\"", "£", "$", "%", "^", "*", "(", ")", "{", "}", ":", ";", "@", "~", "#", "<", ">", "?", "/", "\", "|", "`", "¬");
The above array hols all the characters that would cause a URL to error or not be formatted properly by apache.
Next we need to replace these characters with something if we find them. For this we use PHP's str_replace() function.
So when we pass a string to our function it removes any unwanted characters and stores the nicely formed string in the $URL variable. So all we need to do now is to return our $URL variable from our function.
return $URL;
This is how our function will look:
<?php function createURL( $string ) { $deleteChars = array(" ", "-", ".", ",", "&", "=", "+", "!", "\"", "£", "$", "%", "^", "*", "(", ")", "{", "}", ":", ";", "@", "~", "#", "<", ">", "?", "/", "\", "|", "`", "¬"); $URL = str_replace( $deleteChars, "_", $string ); return $URL; } ?>
What our above function will do, is provide us with a string that we can use for our URL's without containing any characters that can cause errors and that are not useful for SEO purposes.
Here is an example of how to use this function:
$myString = createURL( "myUrl&yourURL" ); $myURL = "/content/{$myString}/";