1

hey, i have this path name from an input element interesse[angebote][flurfuerderfahrzeuge] as a string in my php var. now i need convert it somehow (with regex or explode()) so it looks like this: $_POST['interesse']['angebote']['flurfuerderfahrzeuge'] and the use eval() to get the value. But I'm sure there must be a much easier way do this. Any ideas? Thanks!

1
  • eval on an input element? That's asking for chaos, friend. That's asking for chaos. Commented May 28, 2010 at 16:13

2 Answers 2

2

eval() is evil(). And there are some faster options to avoid it in this case.

If you just want to convert the syntax, then I have a regex:

  $name = '$' . preg_replace("/\[([^\]]+)\]/", '["$1"]', $path);

If your input string not only contains the path, but also an value (attach a dummy value if you must), then you can just use parse_str() to extract the array names into a real PHP array:

  $path = "whatever[subname][deepnesting]=1";
  parse_str($path, $as_var);
  print_r($as_var);

Tell something more about your input data.


Okay, just figured out what you mean. You want to submerge in the $_POST array. Then use step-wise references like so:

$path = "xxxx[yyyy][zzzz]";
$ref = & $_POST;

preg_match_all("/\w+/", $path, $uu);
foreach ($uu[0] as $subname) {
   $ref = & $ref[$subname];
}

print_r($ref);   // = $_POST[xxxx][yyyy][zzzz]
Sign up to request clarification or add additional context in comments.

2 Comments

no i dont have the input, if i had the input this hack would be pointless.
awesome and elegant solution, thank you. not sure why you've used references.
0

ok i know its simple but i looks so ugly, thats what i use now:

    $path = 'interesse[angebote][flurfuerderfahrzeuge]';
    $post_var = '$_POST['.str_replace(']]', ']', str_replace('[', '][', $path));
    eval('$value = '.$post_var.';');
    echo $value;

4 Comments

You should worry about someone passing 'interesse[angebote][flurfuerderfahrzeuge]; unlink("somefile");'
haha i would never parse the post data :D. the $path var is hardcoded by me.
I see. I read i have this path name from an input element and assumed it would be from input.
ye your right, asking questions after 9h programming isn't wise.

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.