开发者

Convert a string into an array

I have the following string:

开发者_C百科
key:surname +++ value:Tesla|||key:name +++ value:Nikola|||key:age +++ value:86|||

How with the PHP I can convert it into an associative array? Like:

echo $arr['surname'];
Tesla

I'm trying it, but can't write a correct expression:

$str= "key:surname +++ value:Tesla|||key:name +++ value:Nikola|||key:age +++ value:86|||"; 
preg_match_all("regex_here",$str,$out); 
unset($out[0]); 
$out = array_combine($out[1],$out[2]) ; 
print_r($out); 

Thanks.


This should do what you need:

$str= "key:surname +++ value:Tesla|||key:name +++ value:Nikola|||key:age +++ value:86|||"; 
preg_match_all("/key:(.*?) \+\+\+ value:(.*?)\|\|\|/", $str, $out);
$out = array_combine($out[1], $out[2]) ; 
print_r($out);

As mentioned by others, though, if you're the one storing the data like that, there are many better ways to store the data, including serializing and JSON, which you might want to look into.


Something like this:

preg_match_all("/:(\w+).*?:(\w+)/", $str, $matches);
var_dump(array_combine($matches[1], $matches[2]));


why there has three + and three | . If it's you make it that. I think you could change it to one. Then the explode function can help you !

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜