在数组中获取子字符串出现的次数

3

我想要在数组中统计一个子字符串出现的次数。因为这是Drupal网站,所以我需要使用PHP代码。

$ar_holding = array('usa-ny-nyc','usa-fl-ftl', 'usa-nj-hb', 
                    'usa-ny-wch', 'usa-ny-li');

我需要能够调用类似于foo($ar_holding, 'usa-ny-');这样的函数,并从$ar_holding数组中返回3。我知道in_array()函数,但它只返回字符串第一次出现的索引。我需要该函数搜索子字符串并返回计数。

4个回答

6
您可以使用 preg_grep() 来实现:
$count = count( preg_grep( "/^usa-ny-/", $ar_holding ) );

这将统计以"usa-ny-"开头的值的数量。如果您想包含包含该字符串的任何位置的值,请删除插入符(^)。
如果您想要一个可以用于搜索任意字符串的函数,您还应该使用preg_quote()
function foo ( $array, $string ) {
    $string = preg_quote( $string, "/" );
    return count( preg_grep( "/^$string/", $array ) );
}

3
如果您需要从字符串开头进行搜索,可以使用以下方法:
$ar_holding = array('usa-ny-nyc','usa-fl-ftl', 'usa-nj-hb', 
                    'usa-ny-wch', 'usa-ny-li');

$str = '|'.implode('|', $ar_holding);

echo substr_count($str, '|usa-ny-');

它使用implode函数将所有数组值与|字符连接在一起(并在第一个元素之前),因此您可以使用搜索术语搜索此前缀。然后,substr_count执行实际操作。 |充当控制字符,因此它不能成为数组中的值的一部分(这不是情况),只是说以防数据发生更改。

1
$count = subtr_count(implode("\x00",$ar_holding),"usa-ny-");

\x00 的作用是几乎可以确定你不会因为将数组连接在一起而导致匹配重叠(唯一可能发生的情况是搜索 null 字节时)。


1
如果数组包含像“usa-ny-foobar-usa-ny-whatever”这样的值,那么返回的计数可能会比预期的要大。诚然,在这个例子中似乎不太可能出现这种情况,但值得注意的是。(如果您只想要锚定匹配,可以使用hakre的技巧在搜索字符串中包含分隔符。) - Ilmari Karonen

0

我看不出任何过度复杂化这个任务的理由。

迭代数组,并在每次值以搜索字符串开头时将计数加1。

代码:(演示:https://3v4l.org/5Lq3Y

function foo($ar_holding, $starts_with) {
    $count = 0;
    foreach  ($ar_holding as $v) {
        if (strpos($v, $starts_with)===0) {
            ++$count;
        }
    }
    return $count;
}

$ar_holding = array('usa-ny-nyc','usa-fl-ftl', 'usa-nj-hb', 
                    'usa-ny-wch', 'usa-ny-li');
echo foo($ar_holding, "usa-ny-");  // 3

或者,如果您不希望声明任何临时变量:

function foo($ar_holding, $starts_with) {
    return sizeof(
        array_filter($ar_holding, function($v)use($starts_with){
             return strpos($v, $starts_with)===0;
        })
    );
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接