Create URL friendly strings like WordPress
2010-01-16 @ 14:59WordPress 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
Det+h%E4r+%E4r+ett+%22citat%22+i+en+url
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
<?php $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
det-har-ar-ett-citat-i-en-url
2012-04-05 @ 9:37 f m
Tack, detta var precis det jag letade efter