PHP - Clean up a string

December 2016



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-ccm-is-great


Related :

This document entitled « PHP - Clean up a string » from CCM (ccm.net) is made available under the Creative Commons license. You can copy, modify copies of this page, under the conditions stipulated by the license, as this note appears clearly.