Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Case insensitive string comparison

I would like to compare two variables to see if they are the same, but I want this comparison to be case-insensitive.

For example, this would be case sensitive:

if($var1 == $var2){    ... } 

But I want this to be case insensitive, how would I approach this?

like image 402
Deniz Zoeteman Avatar asked Mar 29 '11 13:03

Deniz Zoeteman


People also ask

How do you compare strings to ignore cases?

The equalsIgnoreCase() method compares two strings, ignoring lower case and upper case differences. This method returns true if the strings are equal, and false if not. Tip: Use the compareToIgnoreCase() method to compare two strings lexicographically, ignoring case differences.

Is == case-sensitive in JS?

JavaScript is a case-sensitive language. This means that the language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

Is string comparison in SQL case-sensitive?

A string comparison is case sensitive when you don't want it to be, or vice versa.

What is a case-insensitive string?

Java String equalsIgnoreCase() method is used to compare a string with the method argument object, ignoring case considerations. In equalsIgnoreCase() method, two strings are considered equal if they are of the same length and corresponding characters in the two strings are equal ignoring case.


2 Answers

This is fairly simple; you just need to call strtolower() on both variables.

If you need to deal with Unicode or international character sets, you can use mb_strtolower().

Please note that other answers suggest using strcasecmp()—that function does not handle multibyte characters, so results for any UTF-8 string will be bogus.

like image 172
asthasr Avatar answered Oct 15 '22 11:10

asthasr


strcasecmp() returns 0 if the strings are the same (apart from case variations) so you can use:

if (strcasecmp($var1, $var2) == 0) { } 
like image 32
Ramon Avatar answered Oct 15 '22 10:10

Ramon