我有一个很长的字符串和一组国名。所以阵列看起来像这样:如何计算长字符串中多个模式的出现次数?
array('Afghanistan', 'Bulgaria', 'United States', 'Bulgaria', ...)
我需要计算每个国家出现在字符串中的次数。 有没有这样做的快速和漂亮的方式,即某种神奇的preg_match_all接收一组模式,或者我必须遍历所有国家?
我有一个很长的字符串和一组国名。所以阵列看起来像这样:如何计算长字符串中多个模式的出现次数?
array('Afghanistan', 'Bulgaria', 'United States', 'Bulgaria', ...)
我需要计算每个国家出现在字符串中的次数。 有没有这样做的快速和漂亮的方式,即某种神奇的preg_match_all接收一组模式,或者我必须遍历所有国家?
您可以使用类似:
$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!
我不认为你可以用一次调用完成它,但是当你迭代substr_count()时,可能会比preg_ *更快。
我只是用一个哈希表(关联数组)和环路通过你的国家:
// 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";
}
如果你想要的东西极快的(但不是快速实施),考虑Aho Corasick's algorithm。 Here是PHP中的一个实现。
尝试使用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;
}
我希望这是你要找的人!
备案,数组不是字符串。这是两个截然不同的问题。 – GSto 2009-10-02 21:06:19
我相信他知道这一点,他有一个很大的字符串数组。 – Lizard 2009-10-02 21:21:50
要小心这样的句子:'在保加利亚人被称为保加利亚人'。您可能会将“保加利亚”一词计为两次,而只有一次可能需要。 – 2009-10-03 08:20:13