Home » PHP, Regular Expression22 April 2010

PHP: Simple and easy way to format URL string

Here, I will be showing you a simple and easy one line code to format URL string with PHP. By URL string, I mean the url key in any Search Engine Friendly URL.

I have used preg_replace function to do so.

preg_replace($pattern, $replacement, $string)

preg_replace function performs a regular expression search and replace. This will search subject for matches to pattern and replaces them with replacement.

Here is my code:-

e.g. http://example.com/my-planet-earth/

I am talking about formatting ‘my-planet-earth’. Here, $string can be ‘My Planet Earth’ and the $urlKey will be ‘my-planet-earth’

Hope this helps. Thanks.

Regular Expression

Get New Post by Email

Find me on

FacebookTwitterGoogle+LinkedInRSS Feed