2012-05-30 66 views
0

我正在尋找一種簡便地提取包含多個鍵的字符串的方法。該字符串的結果形成一個捲曲頭響應從包含多個鍵的字符串中提取鍵

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

期望的結果:

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

array (
    [status] => '2' 
    [reason] => 'Invalid tariff/currency' 
) 
+1

這實際上取決於您可以如何很好地預測該數據的形式......例如,如果鍵 - 值對總是由空格分隔並且使用等號運算符分配,則可以使用簡單的preg_match應該解析出來。 –

+1

鏈接http://stackoverflow.com/questions/4923951/php-split-string-in-key-value-pairs http://php.net/manual/en/function.parse-str.php – Uttara

回答

0

像這樣,也許?

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

var_dump($data); 
0

鑑於上面的字符串,可以創建本地變量$status$reason使用PHP Variable variables。看看下面的代碼:

$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 
0

試試這個,它會工作只爲你的榜樣,我建議更好的preg_match去,如果你有不同的格式提取數據的可能性。

$response['body'] = "status=2 reason=Invalid tariff/currency"; 
$responseArray = explode(" ", $response['body'], 2); 
foreach($responseArray as $key => $value){ 
    $requiredOutput = explode("=",$value); 
    print_r($requiredOutput); 
} 
相關問題