David Stockdale's Scrapcode

How to add up all numbers in a sentence

I often find myself forgetting how to get the sum of all numbers in an ordinary sentence String.

This is the solution I often use for doing it in PHP:

$string = 'Germany = 28, United States = 286, United Kingdom = 6, Russia = 38, France = 26, Poland = 2, Turkey = 1, Austria = 1, Hungary = 3, India = 2, Moldova = 3, Australia = 2, Cyprus = 1, Belgium = 1, South Africa = 1, Switzerland = 1, Hong Kong = 2, Denmark =';

preg_match_all('!\d+!', $string, $matches);

print_r(array_sum($matches[0]));

Which returns:

404

This came in handy for me when I wanted a quick and dirty way to add up all of the comments I get from various countries.

/**
 * Adds the "read_locations" shortcode.
 * [read_locations]
 */
add_shortcode('read_locations', 'read_locations');
/**
 * Reads the rows of the "locations" table.
 */
function read_locations() {
	global $wpdb;
	$row = $wpdb->get_results("SELECT * FROM `locations` LIMIT 1");
	$result = $row[0];
	return implode(get_object_vars($result));
}

/**
 * Adds the "total_locations" shortcode.
 * [total_locations]
 */
add_shortcode('total_locations', 'total_locations');
/**
 * Adds up the numbers returned by the "read locations" shortcode.
 */
function total_locations() {
	$string = do_shortcode('[read_locations]');
	
	preg_match_all('!\d+!', $string, $matches);
	
	return("Total comments: " . array_sum($matches[0]));
}

Leave a Reply