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.
The assignment operator assigns the variable on the left to have a new value as the variable on right, while the equal operator == tests for equality and returns true or false as per the comparison results. Example: This example describes the string comparison using the == operator.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
php $transliterator = Transliterator::createFromRules(':: NFD; :: [:Nonspacing Mark:] Remove; :: NFC;', Transliterator::FORWARD); $test = ['abcd', 'èe', '€', 'àòùìéëü', 'àòùìéëü', 'tiësto']; foreach($test as $e) { $normalized = $transliterator->transliterate($e); echo $e.
The strcmp() function compares two strings. Note: The strcmp() function is binary-safe and case-sensitive. Tip: This function is similar to the strncmp() function, with the difference that you can specify the number of characters from each string to be used in the comparison with strncmp().
I would like to share an elegant solution that avoids the usage of htmlentities and that doesn't need to manually list all chars replacements. It is the traduction in php of the answers to this post.
function removeAccents($str) {
return preg_replace('/[\x{0300}-\x{036f}]/u',"",normalizer_normalize($str,Normalizer::FORM_D));
}
$a = "joaoaaeeA";
$b = "joãoâàéèÀ";
var_dump(removeAccents($a) === removeAccents($b));
Output:
bool(true)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With