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.

/**
 * 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;
}
Snippet Details



/**
 * Examples:
 */
 
print FormatAsKey("** this + that = something **") . "\n";
print FormatAsKey("100% freeware!") . "\n";
print FormatAsKey("Das ist übermäßig öffentlich") . "\n";
print FormatAsKey("Another sentence...") . "\n";
 
/*
Output:
 
this-plus-that-equals-something
100-percent-freeware
das-ist-uebermaessig-oeffentlich
another-sentence-dot-dot-dot
*/

Sorry folks, comments have been deactivated for now due to the large amount of spam.

Please try to post your questions or problems on a related programming board, a suitable mailing list, a programming chat-room,
or use a QA website like stackoverflow because I'm usually too busy to answer any mails related
to my code snippets. Therefore please just mail me if you found a serious bug... Thank you!


Older comments:

None.