webCOMAND

string_util::get_key_value_pairs()

Return associative array of key/value pairs based on a string, regex and options to capture and validate the string.

An \io_comand\exception will be thrown if anything unexpected is encountered while processing, or if all desired keys are not found.

Prototype

string get_key_value_pairs(mixed $lines, string $regex, array $options = [])

Parameters

  • lines - String of separated lines, or an array of lines, containing key/value pairs.
  • regex - Regex to be processed by preg_match() to capture the key/value pairs, where key is matches[1] and value is matches[2].
  • options - Associative array of options, including:
    • keys - Array of desired keys to be validated and returned.  If not specified, all key/value pairs will be returned.
    • separator - key/value pair separator.  Will use "\n" is not specified.

Return

An associative array of key/value pairs.

Example

use \io_comand_util\string_util;

$meminfo = file_get_contents('/proc/meminfo');
 
try {
    // create associative array of values based on regex
	$values = string_util::get_key_value_pairs(
        $meminfo,
        '/^([^:]+):\s+(\d+)( kB)?$/',
        ['keys' => ['MemTotal', 'MemFree', 'MemAvailable']]
    );
} catch(\io_comand\exception $e) {
	throw new \Exception('Invalid meminfo: ' . $e->getMessage());
}

$total = (int)$values['MemTotal'] * 1024;
$free = (int)$values['MemFree'] * 1024;
$available = (int)$values['MemAvailable'] * 1024;