PHP数组中不区分大小写的搜索

问题描述 投票:-1回答:1

我要搜索移动设备或移动设备图例或移动设备。它应该返回两个数组。但是我的代码仅在我搜索完全相同的单词时才有效。请帮助。

$resutls = [];
$words = ['mobile', 'Mobile Legend', 'Mobile', 'mobile legend']; 

foreach ($items as $item) {
   if(in_array($item['CategoryName'], $words)) {
      $results[] = $item;
   }
}
print_r($results);

[0] => Array
        (
            [id] => 1
            [Name] => Mobile Game,
            [CategoryName] => Mobile Legend
        )
     [1] => Array
        (
            [id] => 2
            [Name] => Laptop Game
            [CategoryName] => Mobile
        )
php arrays search
1个回答
0
投票

这可能是您要寻找的:

<?php

$search = "mobile";


$input = ['mobile', 'Mobile Legend', 'Mobile', 'mobile legend', 'desktop']; 
$output = [];
$pattern = sprintf('/%s/i', preg_quote($search));

array_walk($input, function($entry) use ($pattern, &$output) {
  if (preg_match($pattern, $entry)) {
    $output[] = $entry;
  }
});

print_r($output);

明显的输出是:

Array
(
    [0] => mobile
    [1] => Mobile Legend
    [2] => Mobile
    [3] => mobile legend
)
© www.soinside.com 2019 - 2024. All rights reserved.