我想获得一个子串在数组中出现多少次的计数。这是针对Drupal网站的,因此我需要使用PHP代码
$ar_holding = array('usa-ny-nyc','usa-fl-ftl', 'usa-nj-hb',
'usa-ny-wch', 'usa-ny-li');
Run Code Online (Sandbox Code Playgroud)
我需要能够调用类似的函数foo($ar_holding, 'usa-ny-');并使它从$ar_holding数组中返回3 。我知道该in_array()函数,但是它返回字符串首次出现的索引。我需要该函数来搜索子字符串并返回一个计数。
您可以使用preg_grep():
$count = count( preg_grep( "/^usa-ny-/", $ar_holding ) );
Run Code Online (Sandbox Code Playgroud)
这将计算以“ usa-ny-”开头的值的数量。如果要在任何位置包括包含字符串的值,请删除插入符号(^)。
如果您想要一个可用于搜索任意字符串的函数,则还应该使用preg_quote():
function foo ( $array, $string ) {
$string = preg_quote( $string, "/" );
return count( preg_grep( "/^$string/", $array ) );
}
Run Code Online (Sandbox Code Playgroud)