0

I'm searching for a way to easly extract a string containing multiple keys. The string is a result form a curl header response

echo $response['body'];
// status=2 reason=Invalid tariff/currency

Desired result:

$status == '2';
$reason == 'Invalid tariff/currency';

or

array (
    [status] => '2'
    [reason] => 'Invalid tariff/currency'
)
Bjoern
  • 15,934
  • 4
  • 43
  • 48
user1425364
  • 35
  • 1
  • 1
  • 5
  • 1
    It really depends on how well you can predict the form of that data... For example, if the key-value pairs are always separated by a space and are assigned using the equals operator, then a simple preg_match should parse them out. – Brian Adkins May 30 '12 at 07:23
  • 1
    links http://stackoverflow.com/questions/4923951/php-split-string-in-key-value-pairs http://php.net/manual/en/function.parse-str.php – Uttara May 30 '12 at 07:24

3 Answers3

0

Something like this, perhaps?

$parts = explode(" ", $response['body'], 2);
foreach($parts as $part)
{
   $tmp = explode("=", $part);
   $data[$tmp[0]] = $tmp[1];
}

var_dump($data);
Repox
  • 15,015
  • 8
  • 54
  • 79
0

Given the string above, you can create local variables $status and $reason using PHP Variable variables. Take a look at this code:

$str = 'status=2 reason=Invalid tariff/currency';

foreach (explode(' ', $str, 2) as $item) {
    list($key, $val) = explode('=', $item);
    $$key = $val;
}

// Now you have these
echo $status;  // 2
echo $reason;  // Invalid tariff/currency
flowfree
  • 16,356
  • 12
  • 52
  • 76
0

try this, it will work only for your example, I suggest better to go with preg_match if you have possibility of extracting data from different formats.

$response['body'] = "status=2 reason=Invalid tariff/currency";
$responseArray = explode(" ", $response['body'], 2);
foreach($responseArray as $key => $value){
    $requiredOutput = explode("=",$value);
    print_r($requiredOutput);
}
Sanjay
  • 1,570
  • 1
  • 13
  • 30