Create URL friendly strings like WordPress

2010-01-16 @ 14:59

WordPress rewrite their URLs in a beautiful way which makes them very user friendly. I’ve created a function that converts a string to be user friendly, the WordPress way.

Don’t use urlencode

In PHP there is a function to convert strings to be URL friendly. The function is called urlencode.

Function call – urlencode

$string = 'Det här är ett "citat" i en url';
echo urlencode($string);

Printed out on the screen


Unfortunately, it doesn’t look very good.

Use super_urlencode instead

The advantage of super_urlencode is that the string looks much better for humans. This version of super_urlencode is made for swedish characters but works fine with english URLs as well.

Function – super_urlencode

$string = 'Det här är ett "citat" i en url';

function super_urlencode($string)
     $string = trim($string);
     $string = strtolower($string);
     $string = str_replace(array('å', 'ä', 'ö', ' '), array('a', 'a', 'o', '-'), $string);
     $string = preg_replace("/[^a-z0-9-]/", "", $string);
     $string = preg_replace("/[-]+/", "-", $string);

     return $string;
echo super_urlencode($string);

Function call – super_urlencode

$string= 'Det här är ett "citat" i en url';
echo super_urlencode($string);

Printed out on the screen

RSS-feed for comments

One reply to “Create URL friendly strings like WordPress”

Leave a reply