简体   繁体   中英

Get count of substring occurrence in an array

I would like to get a count of how many times a substring occurs in an array. This is for a Drupal site so I need to use PHP code

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

I need to be able to call a function like foo($ar_holding, 'usa-ny-'); and have it return 3 from the $ar_holding array. I know about the in_array() function but that returns the index of the first occurrence of a string. I need the function to search for substrings and return a count.

You could use preg_grep() :

$count = count( preg_grep( "/^usa-ny-/", $ar_holding ) );

This will count the number of values that begin with "usa-ny-". If you want to include values that contain the string at any position, remove the caret ( ^ ).

If you want a function that can be used to search for arbitrary strings, you should also use preg_quote() :

function foo ( $array, $string ) {
    $string = preg_quote( $string, "/" );
    return count( preg_grep( "/^$string/", $array ) );
}

If you need to search from the beginning of the string, the following works:

$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-');

It makes use of the implode function to concat all array values with the | character in between (and before the first element), so you can search for this prefix with your search term. substr_count does the dirty work then.

The | acts as a control character, so it can not be part of the values in the array (which is not the case), just saying in case your data changes.

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

\\x00几乎可以肯定,你最终不会因为将数组连接在一起而导致匹配重叠(唯一的一次是它会发生,如果你正在搜索空字节)

I don't see any reason to overcomplicate this task.

Iterate the array and add 1 to the count everytime a value starts with the search string.

Code: (Demo: 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

Or if you don't wish to declare any temporary variables:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM