Post Slug in PHP
What’s post slug?
I actually don’t know how to explain it but I try: It’s a conversion of title (phrase, words) into a more friendly way for the browser.
But better an example:
Before:
This is a “really” long title with weird symbols! (or, not?). It’s meant to be shorter.
After:
this-is-a-really-long-title-with-weird-symbols-or-not-its-meant-to-be-shorter
To do this in php I use this function that I wrote:
function friendly_url($url) { // everything to lower and no spaces begin or end $url = strtolower(trim($url)); //replace accent characters, depends your language is needed //$url=replace_accents($url); // decode html maybe needed if there's html I normally don't use this //$url = html_entity_decode($url,ENT_QUOTES,'UTF8'); // adding - for spaces and union characters $find = array(' ', '&', '\r\n', '\n', '+',','); $url = str_replace ($find, '-', $url); //delete and replace rest of special chars $find = array('/[^a-z0-9\-<>]/', '/[\-]+/', '/<[^>]*>/'); $repl = array('', '-', ''); $url = preg_replace ($find, $repl, $url); //return the friendly url return $url; }
If your language includes any “weird character” please use this function as well (It’s commented in the first one).
function replace_accents($var){ //replace for accents catalan spanish and more //acccents $var = ereg_replace("(À|Á|Â|Ã|Ä|Å|à|á|â|ã|ä|å)","a",$var); $var = ereg_replace("(È|É|Ê|Ë|è|é|ê|ë)","e",$var); $var = ereg_replace("(Ì|Í|Î|Ï|ì|í|î|ï)","i",$var); $var = ereg_replace("(Ò|Ó|Ô|Õ|Ö|Ø|ò|ó|ô|õ|ö|ø)","o",$var); $var = ereg_replace("(Ù|Ú|Û|Ü|ù|ú|û|ü)","u",$var); //ntilde $var = ereg_replace("(Ñ|ñ)","n",$var); //cedilla $var = ereg_replace("(Ç|ç)","c",$var); $var = ereg_replace("ÿ","y",$var); return $var; }
Related posts:
