English 中文(简体)
A. 阵列中的次量发生率
原标题: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 );

我需要能够把以下职能称为:foo($ar_holding, usa-ny- );,并将其从$ar_holding阵列中退回3。 我知道in_array(>)的功能,但这种功能又回到了头一次剧的指数。 我需要寻找替代物并退还计票。

最佳回答

You could use preg_grep():

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

这将计算从“沙-尼”开始的数值数目。 如果你想要列入任何职位上载有该指示的数值,则删除该指示(^)。

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

它利用<代码>implode功能,将所有阵列价值与>> 代码(和在第一个要素之前)的特性混在一起,因此,你可以用你的搜索术语查找这一序号。 <代码>substr_count时, d脏工作就是如此。

<代码>>作为控制特性,因此不能成为阵列中的价值的一部分(情况并非如此),只是说如果数据发生变化。

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

<条码>x<>00是你赢得的几乎最终导致重叠,同时加入阵列(如果你重新寻找无异物的话,会发生的唯一时间)





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签