4

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

5
  • i want to convert string to array with the following output, can you tell me how can it possible Commented Apr 2, 2012 at 12:19
  • You didn't answer my question. What have you tried so far? We aren't going to code for you. Commented Apr 2, 2012 at 12:21
  • @jassi9911 try preg_match_all() Commented Apr 2, 2012 at 12:22
  • i tried using explode function but didn't get the exact output what i want it. Commented Apr 2, 2012 at 12:24
  • where do you get such a string from? Commented Apr 2, 2012 at 12:25

3 Answers 3

2

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.

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

Comments

1

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 #

Comments

0

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().

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.