PHP - Clean up a string

Ask a question


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

Jean-François Pillou

CCM is a leading international tech website. Our content is written in collaboration with IT experts, under the direction of Jeff Pillou, founder of CCM.net. CCM reaches more than 50 million unique visitors per month and is available in 11 languages.

Learn more about the CCM team

Related