面对parse_str()的问题,将+字符替换为空格

时间:2019-03-15 09:07:39

标签: php regex urlencode

我有以下字符串网址:

  

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

我需要提取数组中的键值对。我在PHP中使用了parse_str(),下面是我的代码:

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

输出:

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

您可以在SharedAccessKey字符+中用space替换此问题,我提到了Similiar Question,根据答案,标记的答案不是正确的答案OP方案,这表示首先执行urlencode(),然后传递它,因为parse_str()首先解码URL,然后分离键值,但这将返回单个数组的数组对象,该数组对象按原样返回整个字符串就我而言,其输出如下:

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

请帮帮我,不仅是+字符,而且所有字符都应与parse_str()的字符相同

2 个答案:

答案 0 :(得分:1)

您可以尝试使用preg_match_all模拟parse_str

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

输出:

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

Demo on 3v4l.org

答案 1 :(得分:0)

$ str =“ HostName = MyHostName&SharedAccessKeyName = SOMETHING&SharedAccessKey = VALUE + VALUE =”; preg_match_all('/(?:^ | G)(w +)=([^&] +)(?:&| $)/',$ str,$ matches); print_r(array_combine($ matches [1],$ matches [2]));