iori
iori

Reputation: 3506

How to check the first 2 characters ( case-insensitive ) in PHP?

I have a search input box.

enter image description here

I already check for the first 2 characters.

$first_two = substr($search,0,2);

They need to start with BS, so I check them like this :

if ($search AND $first_two == 'bs' ){
 // ... do stuffs
}

After that, I just realize that I don't want to have any restriction on them.

I want my first two character is case-insensitive.

I want to allow BS, Bs, bs and bS.

What do I need to fix in my if (?) to allow these to happens ?

Upvotes: 2

Views: 66

Answers (2)

Rizier123
Rizier123

Reputation: 59701

Use strcasecmp() like this:

if ($search AND strcasecmp($first_two , "bs") == 0)
              //^If both strings are the same (case-insensitive) the function returns 0

Upvotes: 1

Hanky Panky
Hanky Panky

Reputation: 46900

Use a certain case for your comparison, this example uses lower case

$first_two = substr($search,0,2); 
if ($search AND strtolower($first_two) == 'bs' ){
 // ... do stuffs
}

This way BS, Bs, bS will all be converted to bs and your comparison will always work

Upvotes: 5

Related Questions