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-");
The \x00
is to be almost-certain that you won't end up causing overlaps that match by joining the array together (the only time it can happen is if you're searching for null bytes)
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;
})
);
}
精彩评论