2009-10-02 55 views
1

我有一个很长的字符串和一组国名。所以阵列看起来像这样:如何计算长字符串中多个模式的出现次数?

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

我需要计算每个国家出现在字符串中的次数。 有没有这样做的快速和漂亮的方式,即某种神奇的preg_match_all接收一组模式,或者我必须遍历所有国家?

+0

备案,数组不是字符串。这是两个截然不同的问题。 – GSto 2009-10-02 21:06:19

+0

我相信他知道这一点,他有一个很大的字符串数组。 – Lizard 2009-10-02 21:21:50

+0

要小心这样的句子:'在保加利亚人被称为保加利亚人'。您可能会将“保加利亚”一词计为两次,而只有一次可能需要。 – 2009-10-03 08:20:13

回答

1

您可以使用类似:

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

我不认为你可以用一次调用完成它,但是当你迭代substr_count()时,可能会比preg_ *更快。

3

我只是用一个哈希表(关联数组)和环路通过你的国家:

// 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"; 
} 
+2

我不确定这是他之后的......我认为他有一串带有大量其他文字的字符串,并且想要统计该字符串中每个国家的发生情况。 – Lizard 2009-10-02 21:21:18

+0

但它是辉煌的 – slikts 2009-10-02 22:33:18

2

尝试使用substr_count 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; 
} 

我希望这是你要找的人!

+1

谢谢,这将工作 - 但它是区分大小写的。所以,如果我在文中有保加利亚文,那么它不会奏效。 – Sleepster 2009-10-02 21:33:45

+0

之前做一个strtolower()。 – Toto 2009-10-02 22:35:30

+0

请检查我的编辑,因为这将解决您的大小写敏感问题。 – Lizard 2009-10-03 08:14:34

相关问题