English 中文(简体)
如何在很长的时间里计算多种模式的发生?
原标题:How to count the occurences of multiple patterns in a long string?
  • 时间:2009-10-02 20:47:13
  •  标签:

我有很长的路要走,有许多国名。 因此,阵列看着这样的情况:

array( Afghanistan ,  Bulgaria ,  United States ,  Bulgaria , ...)

I need to count the number of times each country appears in the string. Is there a quick and nifty way of doing this, i.e., some kind of magical preg_match_all which receives an array of patterns, or must I iterate through all countries?

最佳回答

你们可以使用这样的东西:

$country_names = array( Afghanistan ,  Bulgaria ,  United States , ...);
$country_names_preg = "/(" . implode("|", $country_names) . ")/";
preg_match_all($country_names_preg, $long_string, $matches);

//$matches will contain all of the country matches.
$echo "found: " . implode(", ", $matches);

// There would ideally be a check to make sure that $matches had something in it!
问题回答

我只是通过贵国使用一个h(联系阵列)和 lo:

// Count:
$country_names = array( Afghanistan ,  Bulgaria ,  United States , ...);
$country_count = array();
foreach ($country_names as $name) {
  $country_count[$name]++;
}

// Then display:
foreach ($country_names as $name) {
  echo "Found " . $country_count[$name] . " occurrences of $name.
";
}

如果您希望得到一些空白(但并不迅速执行),则考虑Aho Corasicks s. Here s implementation in PHP。

我不认为你可以用一个电话这样做,但是,虽然你通过子公司重新开张,可能比预想的更快。





相关问题
热门标签