phpcase-insensitivestrpos

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

Solution

  • 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