问题
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