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

僤鯓⒐⒋嵵緔 提交于 2019-12-22 04:43:34

问题


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.


回答1:


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'))), ' '));
}

$a = "joaoaaeeA";
$b = "joãoâàéèÀ";

var_dump(removeAccents($a) === removeAccents($b));

Output:

bool(true)

Demo




回答2:


It's not a plain PHP solution but works very well for this situation, run this query on MySQL:

SELECT 'joão' = 'joao'

So if you have access to mysql you can use it from PHP.



来源:https://stackoverflow.com/questions/27680624/compare-two-string-and-ignore-but-not-replace-accents-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!