Monday, 24 November 2014

PHP - Clean up a string

A small PHP function which can be quite useful, especially when doing the URL rewriting. This function transforms any accented characters of any string , removing special characters and replacing empty spaces by dashes. 

function string2url($string) {  
 $chaine = trim($string);  
 $chaine = strtr($string,  
"ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ",  
"aaaaaaaaaaaaooooooooooooeeeeeeeecciiiiiiiiuuuuuuuuynn");  
 $chaine = strtr($string,"ABCDEFGHIJKLMNOPQRSTUVWXYZ","abcdefghijklmnopqrstuvwxyz");  
 $chaine = preg_replace('#([^.a-z0-9]+)#i', '-', $string);  
        $chaine = preg_replace('#-{2,}#','-',$string);  
        $chaine = preg_replace('#-$#','',$string);  
        $chaine = preg_replace('#^-#','',$string);  
 return $string;  
}



Example of use: 
<?php   
echo string2url(Don't you think Kioskea is great!!);   
// Will give as result: don-t-you-think-kioskea-is-great

0 comments:

Post a Comment