Ceri Turner
Ceri Turner

Reputation: 936

How to make strpos() match case-insensitively

I have an array which contains badge objects. I'm trying to remove objects that don't match search criteria, at the moment the criteria is if the name doesn't match a searched string

The code I have so far is:

foreach ($badgeList as $key => $badge) {
    $check = strpos($badge->getName(), $_POST['name']);
    if ($check === false) {
        unset($badgeList[$key]);
        print "<br/>" . $badge->getName() . " -- post: " . $_POST['name'];
    }
}

What's happening is its removing all objects from the array, even those that do match the string.

This is what's being printed:

Outdoor Challenge -- post: outdoor

Outdoor Plus Challenge -- post: outdoor

Outdoor Challenge -- post: outdoor

Outdoor Challenge -- post: outdoor

Nights Away 1 -- post: outdoor

Year 1 -- post: outdoor

Nights Away 5 -- post: outdoor

Upvotes: 0

Views: 319

Answers (2)

Michael Curtis
Michael Curtis

Reputation: 393

If you need looser matching, use a case insensitive function or regex:

stristr($badge->getName() , $_POST['name'])

or

if( ! preg_match("/" . $_POST['name'] . "/i",$badge->getName()) ) {

In these suggestions stristr is the case insensitive version of strstr and /i is the case insensitive flag for regex

Upvotes: 1

Marius
Marius

Reputation: 4016

One way of solving this would be as follows:

$check = strpos(strtolower($badge->getName()) , strtolower($_POST['name']));

strtolower() will convert both haystack and needle to lowercase strings and now your search for "string" will match "String" as well.

Your original issue is that strpos() does a case sensitive search ('S' is not the same as 's')

Upvotes: 0

Related Questions