view raw
Penny Penny - 6 months ago 43
PHP Question

Compare two string and ignore (but not replace) accents. PHP

I got (for example) two strings:

$a = "joao";
$b = "joão";

if ( strtoupper($a) == strtoupper($b)) {
echo $b;

I want it to be true even tho the accentuation. However I need it to ignore the accentuation instead of replacing because I need it to echo "joão" and not "joao".

All answers I've seen replace "ã" for "a" instead of making the comparison true. I've been reading about normalizing it, but I can't make it work either. Any ideas? Thank you.


Just convert the accents to their non-accented counter part and then compare strings. The function in my answer will remove the accents for you.

function removeAccents($string) {
    return strtolower(trim(preg_replace('~[^0-9a-z]+~i', '-', preg_replace('~&([a-z]{1,2})(acute|cedil|circ|grave|lig|orn|ring|slash|th|tilde|uml);~i', '$1', htmlentities($string, ENT_QUOTES, 'UTF-8'))), ' '));

if (removeAccents($a) == removeAccents($b)) {
    echo $b;