To improve @Jaquarh's answer, you could write this function that helps you extract the values using any desired string, key and expected type.
I have added a few features to the function like not minding how many spaces come between the =>
separator in the string, any value-type matching, so that it can retrieve both numeric and string values after the =>
separator and trimming of the final string value. Finally, you have the option of casting the final value to an integer if you want - just supply an argument to the $expected_val_type
argument when you call the function.
$my_str
is your API response string, and $key_str
is the key whose value you want to extract from the string.
function key_extractor($my_str, $key_str, $expected_val_type=null) {
// Find match of supplied $key_str regardless of number of spaces
// between key and value.
preg_match("/(\[" . $key_str . "\]\s*=>\s*[\w\s]+)/", $my_str, $matches);
if (!empty($matches)) {
// Retrieve the value that comes after `=>` in the matched
// string and trim it.
$value = trim(substr($matches[0], strpos($matches[0], "=>") + 2));
// Cast to the desired type if supplied.
if ($expected_val_type === 'int') {
return ((int) $value);
}
return $value;
}
// Nothing was found so return null.
return NULL;
}
You could then use it like this:
key_extractor($res, 'status', 'int');
$res
is your API response string.