Jump to content

Explode Nightmare


otonix

Recommended Posts

I am having a nightmare with an explode and cant get it to work. I am posting a string using JQuery to a PHP form which needs to explode the string into an indexed array to be inserted into a database.

 

This is what the string looks like "importance%5B101%5D=50&importance%5B100%5D=50&importance%5B99%5D=50&importance%5B98%5D=50"

 

The original array has been serialised into the above string. The arrayname is importance. The array's index (inside the square brackets) is referenced from an ID from the page.  The square brackets have been replaced by '%5B' and '%5D' and surround the array index by the JQuery. The value for each of these array items is shown as =50. So its basically the same as a GET when we have name=value&name1=value1etc')

 

How would i explode the string above to remove the '%5B' and '%5D' to make the '[' and ']' reappear and then from then it can be read as a GET post? like 'name=value&name1=value1etc'. Using the new array of that index ready to be inserted into a MySQL database.

 

Im going mad trying to solve this!!!  :confused:

Link to comment
Share on other sites

This will convert the string into an array (or arrays) based on the name(s) used in the string. In this case it would be an array variable $importance

$encodedString = "importance%5B101%5D=50&importance%5B100%5D=50&importance%5B99%5D=50&importance%5B98%5D=50";

$decodedString = urldecode($encodedString);
$explodedVars = explode('&', $decodedString);
foreach($explodedVars as $nameValuePair)
{
    preg_match("#(.*)\[([^\]]*)\]=(.*)#", $nameValuePair, $matches);
    ${$matches[1]}[$matches[2]] = $matches[3];
}

print_r($importance);

/*Output---
Array
(
    [101] => 50
    [100] => 50
    [99] => 50
    [98] => 50
)
*/

Link to comment
Share on other sites

Or to get an array, simply this:

 

$s = "importance%5B101%5D=50&importance%5B100%5D=50&importance%5B99%5D=50&importance%5B98%5D=50";

parse_str(urldecode($s), $array);

print_r($array);

 

Damn it! I was thinking there should be a function to do that.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.