update page now
Laravel Live Japan

Voting

: five plus two?
(Example: nine)

The Note You're Voting On

chris at mcfadyen dot ca
18 years ago
I shouldn't've posted the original version, as it only worked with the most basic of query strings.

This function will parse an html-safe query-like url string for variables and php-like ordered and associative arrays.  It places them into the global scope as parse_str does and adds minimal slashes for database insertions without the triple-slash problems that magic quotes can produce (the reason I had to write it in the first place).  If you don't need the slashes, they're easy enough to remove.

<?php
function parse_query($str) {
    
    // Separate all name-value pairs
    $pairs = explode('&', $str);
    
    foreach($pairs as $pair) {
        
        // Pull out the names and the values
        list($name, $value) = explode('=', $pair, 2);
        
        // Decode the variable name and look for arrays
        list($name, $index) = split('[][]', urldecode($name));
        
        // Arrays
        if(isset($index)) {
            
            // Declare or add to the global array defined by $name
            global $$name;
            if(!isset($$name)) $$name = array();
            
            // Associative array
            if($index != "") {
                ${$name}[$index] = addslashes(urldecode($value));
                
            // Ordered array
            } else {
                array_push($$name, addslashes(urldecode($value)));
            }
        
        // Variables
        } else {
            
            // Declare or overwrite the global variable defined by $name
            global $$name;
            $$name = addslashes(urldecode($value));
        }
    }
}
?>

<< Back to user notes page

To Top