0

I am trying to replace the keys of quite a large array so that I only get a spcific piece of data from it. My client pastes in a set of data in a specific format into a text are which is then loaded into a series of columns in a table like so:

textarea data would be like:

rp1=1, rp2=3, rp4=5 etc etc

If I do a var dump on the post I get this:

array(33) { [0]=> string(2) " 8" [1]=> string(5) "RP2=7" [2]=> string(5) "RP3=9" [3]=> string(6)...

What I am trying to do isjust give me the figure from the key so for instance if you look at the var_dump I did I hit the first key with a string replace so I only get 8 in the array series. I am wanting to know a way to attack all of them as some of the strings contain 4 characters and some 5. so like rp1=1 and rp10=2.

They way I get the data from a textarea into an array is by doing this:

$stenData = explode(', ',  $_POST['stenData']);
16
  • show how should look the expected result Commented Mar 1, 2017 at 14:44
  • So you want to cleanup stuff before insert now? I remeber the Q about cleanup data from database with same stuff RP[0-9]+=. You can use that preg_replace here, too. Commented Mar 1, 2017 at 14:45
  • @RomanPerekhrest The end result should be: array(33) { [0]=> string(2) "8" [1]=> string(5) "3" [2]=> string(5) "4" [3]=> string(6)... Commented Mar 1, 2017 at 14:46
  • Like $stenData = array_map('trim',explode(', ',preg_replace('#(RP[0-9]+=)#','',$_POST['stenData']))); Commented Mar 1, 2017 at 14:47
  • @JustOnUnderMillions yeah I do it seems like a much better method because there shouldnt be data in the database like that Commented Mar 1, 2017 at 14:47

1 Answer 1

1

Lot's of ways with array_map(), however if you have a var=num syntax then parse it as a query string instead of constructing a regex:

$result = array_map(function($v) { parse_str($v, $r); return current($r); }, $stenData);

Or to do it from the posted string, just replace , with & to turn it into a query string to parse:

parse_str(str_replace(', ', '&', $_POST['stenData']), $result);

Where $result yields something like:

Array
(
    [rp1] => 1
    [rp2] => 3
    [rp4] => 5
    [TS1] => 7
    [FE1] => 7
)

Since there's all kinds of regex going on in the comments:

preg_match_all('/[^=]=(\d+)/', $_POST['stenData'], $matches);
print_r($matches[1]);
Sign up to request clarification or add additional context in comments.

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.