Format string as machine compatible key


SUBMITTED BY: phpsnippets

DATE: Oct. 21, 2015, 2:14 p.m.

FORMAT: Text only

SIZE: 1.2 kB

HITS: 1746

  1. function FormatAsKey($string){
  2. $string = strtolower($string);
  3. // Fix german special chars
  4. $string = preg_replace('/[äÄ]/', 'ae', $string);
  5. $string = preg_replace('/[üÜ]/', 'ue', $string);
  6. $string = preg_replace('/[öÖ]/', 'oe', $string);
  7. $string = preg_replace('/[ß]/', 'ss', $string);
  8. // Replace other special chars
  9. $specialChars = array(
  10. 'sharp' => '#', 'dot' => '.', 'plus' => '+',
  11. 'and' => '&', 'percent' => '%', 'dollar' => '$',
  12. 'equals' => '=',
  13. );
  14. while(list($replacement, $char) = each($specialChars))
  15. $string = str_replace($char, '-' . $replacement . '-', $string);
  16. $string = strtr(
  17. $string,
  18. "ÀÁÂÃÄÅàáâãäåÒÓÔÕÖØòóôõöøÈÉÊËèéêëÇçÌÍÎÏìíîïÙÚÛÜùúûüÿÑñ",
  19. "AAAAAAaaaaaaOOOOOOooooooEEEEeeeeCcIIIIiiiiUUUUuuuuyNn"
  20. );
  21. // Remove all remaining other unknown characters
  22. $string = preg_replace('/[^a-z0-9\-]/', '-', $string);
  23. $string = preg_replace('/^[\-]+/', '', $string);
  24. $string = preg_replace('/[\-]+$/', '', $string);
  25. $string = preg_replace('/[\-]{2,}/', '-', $string);
  26. return $string;
  27. }

comments powered by Disqus