0

I have the following string:

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.

3
  • 1
    If this is your design of an information storage system, I would suggest you look at json (specifically json_encode and json_decode) as an easier, better designed system. Commented Oct 14, 2011 at 4:26
  • 1
    Just a note: you're aware of PHP's serialize and unserialize functions? See: nz.php.net/manual/en/function.serialize.php Commented Oct 14, 2011 at 4:28
  • What were your tries regarding the regex? Commented Oct 14, 2011 at 4:30

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This doesn't work. It only returns the last match. The array_combine is wrong. Otherwise, a decent solution.
1

Something like this:

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

Comments

0

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 !

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.