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:-


$urlKey = preg_replace(array('/[^a-z0-9-]/i', '/[ ]{2,}/', '/[ ]/'), array(' ', ' ', '-'), $string);

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’


$string = "planet+*&john doe / / \ \ ^ 44 5 % 6 + - @ ku ! ~ ` this";
$urlKey = preg_replace(array('/[^a-z0-9-]/i', '/[ ]{2,}/', '/[ ]/'), array(' ', ' ', '-'), $string);
// outputs: planet-john-doe-44-5-6---ku-this

Hope this helps. Thanks.