Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mschultheiss83/5985178 to your computer and use it in GitHub Desktop.
Save mschultheiss83/5985178 to your computer and use it in GitHub Desktop.
<?php
/**
* Input string parser that keeps variable keys in their original state.
*
* Input string keys containing '-','.',' ' are replaced by PHP with parse_str or $_POST
* with '_'. So &I+have+a+space=value becomes array('I_hava_a_space'=>'value')
*
* With InputStrParser->parseCharacterSafe('I+have+a+space=value') becomes
* array('I hava a space'=>'value')
*
* Usage:
*
* $str = file_get_contents("php://input");
* $Parser = new InputStrParser();
* $data = $Parser->parseCharacterSafe($str);
*
*/
class InputStrParser
{
public function __construct()
{
}
/**
* Attach value $value to array path 'foo[bar]' eg. array('foo'=>array('bar'=>$value))
*
* @param mixed $value
* @param string $path
* @return array
*/
protected function attachValueToArrayPath($value,$path)
{
if( strpos($path, '[') === false )
{
return array($path=>$value);
}
$pathElements = array();
// theres gotta be easier way
while( strpos($path, '[') !== false)
{
$arrayPos = strpos($path, '[');
// Get the next key in the path starting from previous [
$arrayKey = substr($path, 0,$arrayPos);
$pathElements[] = trim($arrayKey);
// Set the next search point in the path
$path = substr($path, $arrayPos+1);
$path = substr_replace($path , "", strpos($path, ']'),1);
}
$pathElements[] = $path;
$pathElements = array_reverse($pathElements);
$return = array();
$pointer = &$return;
do
{
// get key to set
$key = array_pop($pathElements);
// if it is the last key
if(count($pathElements) == 0)
{
// set correct value
$pointer = array($key => $value);
}else
{
// prepare for next key
$pointer[$key]=array();
// move pointer
$pointer = &$pointer[$key];
}
}while(count($pathElements)>0);
return $return;
}
protected function array_merge_phpinput($array1, $array2)
{
if(!is_array($array1))
{
$array1 = array();
}
foreach ( $array2 as $key => &$value )
{
if($key === "")
{
array_push($array1, $value );
}else
{
if ( is_array ( $value ) )
{
if(isset($array1[$key]))
{
$array1[$key] = $this->array_merge_phpinput( $array1[$key], $value );
}else
{
$array1[$key] = $this->array_merge_phpinput( array(), $value );
}
}else
{
$array1[$key] = $value;
}
}
}
return $array1;
}
public function parseCharacterSafe($str)
{
$keyValues = explode("&",$str);
$data = array();
foreach($keyValues as $entry)
{
list($key,$value) = explode("=",$entry);
$key = urldecode($key);
$value = urldecode($value);
$handled = $this->attachValueToArrayPath($value,$key);
$data = $this->array_merge_phpinput($data,$handled);
}
return $data;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment