检查特定文本是否在数组中

时间:2013-09-23 21:41:27

标签: php arrays

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

例如,在阵列中搜索“男人”(“曼联”,“利物浦”,“阿森纳”)目前什么也不返回,但我需要它返回曼联等。

希望有人可以提供帮助

3 个答案:

答案 0 :(得分: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;
});
?>

答案 1 :(得分: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
)

答案 2 :(得分:-1)

尝试这样的事情:

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

foreach($items as $item) {
    if (stripos($item, $searchTerm) !== false) {
        $results[] = $item;
    }
}