Reputation: 21
I want to use array syntax inside a string value and then add that variable in array()
.
Like:
$value= "'user_type'=>'test','username'=>'test'";
$form_data = array($value);
The desired assignment should be:
$form_data = array('user_type'=>'test','username'=>'test');
but this is not what I get.
Upvotes: 1
Views: 616
Reputation: 47992
This is a method using parse_str()
-- which is an intuitive, loop-free one-liner. It seems like the best choice to me -- I mean this is the very purpose of the function! Like any robust solution for this task, it does need careful preparation.
Code: (Demo)
$value= "'user_type'=>'test1','username'=>'test2','monkey\'s wrench'=>'that\'s trouble'";
parse_str(stripslashes(str_replace(["'=>'","','"],['=','&'],trim($value,"'"))),$form_data); // second param is output variable
var_export($form_data);
This will serve you well, unless your "keys" or "values" contain the delimiting substrings.
str_replace()
will modify the delimiters:
'=>'
becomes =
','
becomes &
stripslashes()
handles any escaping slashes.parse_str()
works its magic to directly produce the associative array.My method will not work out-of-the-box on the duplicate link on the question because of the
(string)
prefix and the optional spacing around the delimiting commas. My method is specifically suited to this strictly-structured, one-dimensional, associative, array-like string.
A method using preg_match()
with a carefully designed pattern may be trustworthy, but regex is categorically slower than string functions and may appear a little convoluted to the untrained eye.
A method using eval()
is possible as well, but that function should only be used as a "Plan Z" when all else fails to do the job well AND the values need to be heavily validated/filtered with extreme prejudice.
A method using explode()
and a foreach()
loop will require a larger code block and I assume it will be a slower alternative (but maybe not). Exploding on any single character will run a higher risk of mangling data; like with all solutions extra attention to preserving data intregity is essential.
verjas' method seems a logical approach, but when replacing single quotes with double quotes, keys and values that contain quotes may get mangled. I will leave the preparation code to verjas to accommodate single and double quotes.
Upvotes: 0
Reputation: 1793
I would use a JSON
transformation. This should work:
// create a JSON string like:
$value = '{ "user_type":"test", "username":"test" }';
$form_data = json_decode($value, true);
// test it
var_dump($form_data);
Upvotes: 2