bosh bosh - 1 year ago 71
PHP Question

How to count the occurences of multiple patterns in a long string?

I have a long string, and an array of country names. So the array looks something like this:

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?

Answer Source

You can use something like:

$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!
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download