Uzun bir dize birden desen tekrarlarını saymak nasıl?

5 Cevap php

Ben uzun bir dize, ve ülke adları bir dizi var. Yani dizi şöyle:

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?

5 Cevap

Sen gibi bir şey kullanabilirsiniz:

$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!

Ben sadece bir karma tablo ülkelere yoluyla (ilişkisel dizi) ve döngü kullanmak istiyorum:

// 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.\n";
}

Eğer cayır cayır yanan hızlı (ama uygulamak için hızlı değil) bir şey istiyorsanız, dikkate Aho Corasick's algorithm. Here 's PHP bir uygulama.

Substr_count kullanmayı deneyin http://us3.php.net/manual/en/function.substr-count.php

$yourtmplongstring = strtolower($yourlongstring);
# the above will solve any case sensitive issues
$country_names = array('Afghanistan', 'Bulgaria', 'United States', ...);
$country_count = array();
foreach ($country_names as $name) {
    $occurances = substr_count($name, $yourtmplongstring );
    $country_count[$name] = $occurances;
}

Ben bu aradığınız ne olduğunu umuyoruz!

Ben tek bir çağrı ile bunu yapabileceğimi sanmıyorum, ama substr_count yinelenmesi yaparken () bu amaç için preg_ * daha hızlı olabilir.