Tuesday 23 January 2018

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;
}

/**
 * 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
*/

0 comments:

Post a Comment