Replace diacritic characters with “equivalent” ASCII in PHP?

前端 未结 4 1044
情深已故
情深已故 2021-01-31 20:42

Related questions:

  1. How to replace characters in a java String?
  2. How to replace special characters with their equivalent (such as " á " for &
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-31 20:58

    Try this:

    function normal_chars($string)
    {
        $string = htmlentities($string, ENT_QUOTES, 'UTF-8');
        $string = preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', $string);
        $string = preg_replace(array('~[^0-9a-z]~i', '~-+~'), ' ', $string);
        return trim($string);
    }
    
    Examples:
    
    echo normal_chars('Álix----_Ãxel!?!?'); // Alix Axel
    echo normal_chars('áéíóúÁÉÍÓÚ'); // aeiouAEIOU
    echo normal_chars('üÿÄËÏÖÜŸåÅ'); // uyAEIOUYaA
    

    Based on the selected answer in this thread: URL Friendly Username in PHP?

提交回复
热议问题