Search code examples
phpstring-matchingcase-insensitive

String comparison regardless of case


I'm trying to find different variations of "Username" or "Password" , as shown below, in an case-insensitive manner:

$unVar1 = "username";
$unVar2 = "user name";
$usernameVariations1 = strcasecmp($unVar1, $unVar2);

$unVar3 = "User";
$unVar4 = "id";
$usernameVariations2 = strcasecmp($unVar3, $unVar4);

$pwVar1 = "password";
$pwVar2 = "pass";
$passwordVariations1 = strcasecmp($pwVar1, $pwVar2);

if ($element->value === $usernameVariations1
   || $element->value === $usernameVariations2
   || $element->value === $passwordVariations1) {
  echo "Weee!";
}
else {
  echo "boo!";
}

The problem is it outputs "boo" for each element in the foreach() output. What am I doing wrong? Is it possible to put all of these values in an array? Thanks.


Solution

  • You're making this more complicated then it needs to be. If your usernames and passwords not case sensitive, just make them lowercase when you compare them:

    if (strtolower($username) === strtolower($element->value))
    {
         // ok
    }
    

    Now if you're allowing spaces to be added to the middle, and abbreviations, then you can try plan B:

    $valid_usernames = array('Username', 'username', 'user name', 'UsE Nam');
    if (in_array($element->value, $valid_usernames))
    {
         // ok
    }
    

    Keep in mind that you are now responsible for keeping $valid_usernames complete.