Format string as machine compatible key

This snippet converts a "dirty" string that may contain special characters into a machine compatible nice looking string.

That function works fine for creating urls or ID keys.

Snippet information

Author:
Jonas John

License:
Public Domain

Language:
PHP

Created:
12/09/2007

Updated:
12/09/2007

Tags:


/**
 * Converts a "dirty" string that may contain special 
 * characters into a machine compatible nice looking string. 
 *
 * @param     string    $string         Input string
 * @return    array     Formatted string     
 */ 
function FormatAsKey($string){
 
    $string = strtolower($string); 
 
    // Fix german special chars
    $string = preg_replace('/[äÄ]/', 'ae', $string);
    $string = preg_replace('/[üÜ]/', 'ue', $string);
    $string = preg_replace('/[öÖ]/', 'oe', $string);
    $string = preg_replace('/[ß]/', 'ss', $string);
 
    // Replace other special chars
    $specialChars = array(
        'sharp' => '#', 'dot' => '.', 'plus' => '+', 
        'and' => '&', 'percent' => '%', 'dollar' => '$',
        'equals' => '=', 
    );
 
    while(list($replacement, $char) = each($specialChars))
        $string = str_replace($char, '-' . $replacement . '-', $string);
 
    $string = strtr(
        $string, 
        "ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ", 
        "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn"
    );
 
    // Remove all remaining other unknown characters        
    $string = preg_replace('/[^a-z0-9\-]/', '-', $string);
    $string = preg_replace('/^[\-]+/', '', $string);
    $string = preg_replace('/[\-]+$/', '', $string);
    $string = preg_replace('/[\-]{2,}/', '-', $string);
 
    return $string;
}


Found a bug? Or do you have a better solution for this?
Feel free to leave a message:

Add a comment


Leave a comment