Search code examples
phpregexurlencode

Facing issue with parse_str(), Replacing + char to space


I have the following string url:

HostName=MyHostName;SharedAccessKeyName=SOMETHING;SharedAccessKey=VALUE+VALUE=

I need to extract the key-value pair in an array. I have used parse_str() in PHP below is my code:

<?php
$arr = array();
$str = "HostName=MyHostName&SharedAccessKeyName=SOMETHING&SharedAccessKey=VALUE+VALUE=";
parse_str($str,$arr);
var_dump($arr);

output:

array (
  'HostName' => 'MyHostName',
  'SharedAccessKeyName' => 'SOMETHING',
  'SharedAccessKey' => 'VALUE VALUE=',
)

you can see in the SharedAccessKey char + is replaced by space for this issue, I referred the Similiar Question, Marked answer is not the correct one according to the OP scenario, This says that first do urlencode() and then pass it because parse_str() first decode URL then separate the key-values but this will return array object of a single array which return the whole string as it is like for my case its output is like:

Array
(
    [HostName=MyHostName&SharedAccessKeyName=SOMETHING&SharedAccessKey=VALUE+VALUE=] => 
) 

Please help me out, not for only + char rather for all the characters should come same as they by the parse_str()


Solution

  • You could try emulating parse_str with preg_match_all:

    preg_match_all('/(?:^|\G)(\w+)=([^&]+)(?:&|$)/', $str, $matches);
    print_r(array_combine($matches[1], $matches[2]));
    

    Output:

    Array (
        [HostName] => MyHostName
        [SharedAccessKeyName] => SOMETHING
        [SharedAccessKey] => VALUE+VALUE= 
    )
    

    Demo on 3v4l.org