如何正确拆分含&符号的URL参数为数组
解决URL参数字符串拆分时含&值截断的问题
问题场景
给定参数字符串:
mytext=A & B Company&anothertext=20&texttwo=SampleText&array[1]=10&array[2]=20
使用explode('&', $params)或parse_str()拆分时,mytext的值仅能获取到"A",无法完整拿到"A & B Company"。
原因分析
原始参数字符串不符合URL编码规范:URL中&是参数分隔符,值中的&需要转义为%26。未转义的情况下,explode和parse_str会把值里的&误判为参数分隔符,导致值被截断。
解决方案
方案1:使用正则表达式匹配键值对
通过正则精准匹配键和对应的值(直到下一个参数分隔符&或字符串结尾),避免误判值中的&:
$paramStr = "mytext=A & B Company&anothertext=20&texttwo=SampleText&array[1]=10&array[2]=20"; // 正则匹配:键(不含&和=)= 值(直到下一个&或结尾) preg_match_all('/([^&=]+)=([^&]+)(?=&|$)/', $paramStr, $matches); $params = []; foreach ($matches[1] as $index => $key) { $value = $matches[2][$index]; // 自动转换数字类型 if (is_numeric($value)) { $value = (int)$value; } $params[$key] = $value; } print_r($params);
输出结果:
Array ( [mytext] => A & B Company [anothertext] => 20 [texttwo] => SampleText [array[1]] => 10 [array[2]] => 20 )
方案2:修复原始字符串的编码问题(推荐)
如果能控制参数字符串的生成过程,先对值进行URL编码,确保值中的特殊字符被转义:
// 生成符合规范的参数字符串 $params = [ 'mytext' => 'A & B Company', 'anothertext' => 20, 'texttwo' => 'SampleText', 'array[1]' => 10, 'array[2]' => 20 ]; $encodedParamStr = http_build_query($params); // 此时$encodedParamStr为:mytext=A+%26+B+Company&anothertext=20&texttwo=SampleText&array%5B1%5D=10&array%5B2%5D=20 // 直接用parse_str解析即可 parse_str($encodedParamStr, $result); print_r($result);
这种方式从根源避免了截断问题,是URL参数处理的标准做法。
内容的提问来源于stack exchange,提问作者Saravanan DS
相关产品推荐
相关产品推荐

