Reputation: 1424
I got a result set in array format and i want to make square bracket value as a key and the other one as a value
here is my code
[Name]asdasdasd [Email][email protected] [Phone Number]42342342342 [Subject]dsafsdfsd [Company Name]ZXZXZX [Country]Antarctica
i want output like :- array("name"=>"asdasdasd", "Email"=>"[email protected]");
how can i do this in PHP any help would be greatly appreciated
Thanks Jassi
Upvotes: 4
Views: 5457
Reputation: 20421
You could do:
<?php
$str = '[Name]asdasdasd [Email][email protected] [Phone Number]42342342342 [Subject]dsafsdfsd [Company Name]ZXZXZX [Country]Antarctica ';
preg_match_all('#\[([^\]]+)\]\s*([^\]\[]*[^\]\[\s])#msi', $str, $matches);
$keys = $matches[1];
$values = $matches[2];
// PHP 5
var_dump( array_combine($keys, $values) );
?>
array(6) {
["Name"]=>
string(9) "asdasdasd"
["Email"]=>
string(13) "[email protected]"
["Phone Number"]=>
string(11) "42342342342"
["Subject"]=>
string(9) "dsafsdfsd"
["Company Name"]=>
string(6) "ZXZXZX"
["Country"]=>
string(10) "Antarctica"
}
The regex is a bit more complicated looking, but it basically matches anything but [], allows whitespace in the value and makes sure that the last character isn't [] or whitespace. You could probably get away with ([^\]\[\s]+)
if you knew you were never going to have spaces.
Upvotes: 2
Reputation: 3850
You could adapt this code below for your exact formatting (from this article):
<?php
$assoc_array = array("Key1" => "Value1", "Key2" => "Value2");
$new_array = array_map(create_function('$key, $value', 'return $key.":".$value." # ";'), array_keys($assoc_array), array_values($assoc_array));
print implode($new_array);
?>
Which will output:
Key1:Value1 # Key2:Value2 #
Upvotes: 1
Reputation: 1112
There's no point in someone giving you the exact code, this can be done with some basic functions. Read up on some of the following functions and work something out for yourself, learn ;)
Or if you're feeling adventurous, there's always: preg_match_all()
.
Upvotes: 0