简体   繁体   中英

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

I have a search input box.

在此处输入图片说明

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 ?

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

Use strcasecmp() like this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM