开发者

Converting a string into a key->value array in PHP

if I have a string of key->valu开发者_开发知识库e pairs in the following format:

MIME-Version: 1.0
From: "Tim Lincecum"
Reply-To: "Tim Lincecum"
Return-path: "Tim Lincecum"
Content-Type: text/html; charset=iso-8859-1
Subject: Giants Win World Series!

How do I get an array such that arr['From'] = "Tim Lincecum", etc

I know there's the explode() function, but the only delimiter I see (colon) is in the middle of a key and a value rather than between each pair. How can I approach this?


You could always use regex :)

PHP

$str = 'MIME-Version: 1.0' . "\r\n" .
'From: "Tim Lincecum"' . "\r\n" . 
'Reply-To: "Tim Lincecum"' . "\r\n" . 
'Return-path: "Tim Lincecum"' . "\r\n" . 
'Content-Type: text/html; charset=iso-8859-1' . "\r\n" . 
'Subject: Giants Win World Series!';

preg_match_all('/(.*?):\s?(.*?)(\r\n|$)/', $str, $matches);
 
$headers = array_combine(array_map('trim', $matches[1]), $matches[2]);
 
var_dump($headers);

Output

array(6) {
  ["MIME-Version"]=>
  string(3) "1.0"
  ["From"]=>
  string(14) ""Tim Lincecum""
  ["Reply-To"]=>
  string(14) ""Tim Lincecum""
  ["Return-path"]=>
  string(14) ""Tim Lincecum""
  ["Content-Type"]=>
  string(29) "text/html; charset=iso-8859-1"
  ["Subject"]=>
  string(24) "Giants Win World Series!"
}

See it on IDEone.


$temp = explode("\r\n", $string);
$sets = array();
foreach ($temp as $value) {
    $array = explode(': ', $value);
    $array[1] = trim($array[1], '"');
    $sets[$array[0]] = $array[1];
}

$string is the value you're getting from the database.


Since I did a good guess in comments - I think i need to repeat it here as an answer:

There is a newlines between parameters, so with

$parameters_pairs = explode("\r\n", $parameters_string);

you can split it into the name-value pairs, separated with colon.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜