Using Preg Replace For Search Engine Friendly URLs

I don’t know about you, but I REALLY hate seeing “%20″ in the URL. I haven’t figured out what Google thinks of it yet, but it just looks cheap to me. So when I’m writing SEO friendly URLs, I don’t want to leave any spaces. Let’s assume the title of this particular page is “search engine friendly” and I want to display that in the URL.

If I simply setup my URLs so that “search engine friendly” is placed before “.html” I’m going to have a problem.

search engine friendly.html ends up looking like this:
search%20engine%friendly.html

This is totally unacceptable!!!!

Using the code below I can come out with something that looks like this:
search_engine_friendly.html

This is MUCH better in my opinion.

How did I do it? Easy. I used the pre_replace php function.

Replaces Space With Underscore
$titlelink=preg_replace( ‘/ /’, ‘_’, $title);

Preg_replace works like this:
preg_replace (’/what you are looking for/ ‘, ‘what will replace the thing you are looking for ‘, ‘the variable or value you want to do damage to’ )

Of course, we can go backward with it. If we already have underscores in between each and every space, we can get rid of the underscores and put the spaces back in like this
Replaces Underscore With Space
$title=preg_replace( ‘/_/’, ‘ ‘, $titlelink);

Now we can display the title as we always wanted to.

Leave a Reply

You must be logged in to post a comment.