How to split url parameters with ampersand as array

300 Views Asked by At

I want to split the parameters sent through URL. Here is my text.

"mytext=A & B Company&anothertext=20&texttwo=SampleText&array[1]=10&array[2]=20"

Expected output:

['mytext'=>'A & B Company', 'anothertext'=> 20, 'texttwo' => 'SampleText', array[1] => 10, array[2] => 20 ].

I tried with explode('&', $params) and parse_str($url_components['query'], $params);

both giving only A as result. I need as 'A & B Company'. How to achieve this?

1

There are 1 best solutions below

5
KIKO Software On

I think you're looking for parse_str()?

See: https://3v4l.org/L2UZa

The result is:

array(5) {
  ["mytext"]     => string(2) "A "
  ["B_Company"]  => string(0) ""
  ["anothertext"]=> string(2) "20"
  ["texttwo"]    => string(10) "SampleText"
  ["array"]      => array(2) {
    [1] => string(2) "10"
    [2] => string(2) "20"
  }
}

This differs slight from what you want because of the &. if you could replace the & with the URL encoded version %26 it would work.

See: https://3v4l.org/OXfsD

The result now is:

array(5) {
  ["mytext"]     => string(2) "A & B_Company"
  ["anothertext"]=> string(2) "20"
  ["texttwo"]    => string(10) "SampleText"
  ["array"]      => array(2) {
    [1] => string(2) "10"
    [2] => string(2) "20"
  }
}

Basically the & is an anomaly, it shouldn't have been there in the first place. URL query parameters should be made with urlencode(), or something equivalent, which would have replace & by %26.