0

我需要检查数组中是否有任何特定文本,所以基本上是数组中的 stristr。目前我执行了一个 in_array 函数,但它不会拾取它,因为文本只是数组值的一部分;

例如,在数组中搜索“man”(“Manchester United”、“Liverpool”、“Arsenal”)目前不会返回任何内容,但我需要它来返回 Manchester United 等。

希望有人可以帮助

4

3 回答 3

1
<?php
$teams = array("Manchester United", "Liverpool", "Arsenal");
$term = "man";

foreach ($teams as $team) {
    if (stripos($team, $term) === false) {
        continue;
    }

    echo "Found match: $team\n";
}
?>

或者你可以花哨并使用array_filter:

<?php
$teams = array("Manchester United", "Liverpool", "Arsenal");
$term = "man";
$results = array_filter($teams, function ($elt) use ($term) {
    return stripos($elt, $term) !== false;
});
?>
于 2013-09-23T21:45:30.763 回答
0

像这样的东西怎么样:

function find($needle, array $haystack) {
    $matches = array();
    foreach($haystack as $value) {
        if(stristr($value, $needle) !== false) {
            $matches[] = $value;
        }
    }
    return $matches;
}

$haystack = array("Manchester United", "Liverpool", "Arsenal");
print_r(find('man', $haystack));

输出:

Array
(
    [0] => Manchester United
)
于 2013-09-23T21:45:42.730 回答
-1

尝试这样的事情:

$items = array("Manchester United","Liverpool", "Arsenal");
$results = array();
$searchTerm = 'man';

foreach($items as $item) {
    if (stripos($item, $searchTerm) !== false) {
        $results[] = $item;
    }
}
于 2013-09-23T21:45:49.220 回答