Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string containing dots in php

Tags:

php

parsing

I would parse the following string:

$str = 'ProceduresCustomer.tipi_id=10&ProceduresCustomer.id=1';                 
parse_str($str,$f);

I wish that $f be parsed into:

array(
    'ProceduresCustomer.tipi_id' => '10',
    'ProceduresCustomer.id' => '1'
)

Actually, the parse_str returns

array(
        'ProceduresCustomer_tipi_id' => '10',
        'ProceduresCustomer_id' => '1'
    )

Beside writing my own function, does anybody know if there is a php function for that?

like image 666
gdm Avatar asked Mar 20 '14 16:03

gdm


2 Answers

From the PHP Manual:

Dots and spaces in variable names are converted to underscores. For example <input name="a.b" /> becomes $_REQUEST["a_b"].

So, it is not possible. parse_str() will convert all periods to underscores. If you really can't avoid using periods in your query variable names, you will have to write custom function to achieve this.

The following function (taken from this answer) converts the names of each key-value pair in the query string to their corresponding hexadecimal form and then does a parse_str() on it. Then, they're reverted back to their original form. This way, the periods aren't touched:

function parse_qs($data)
{
    $data = preg_replace_callback('/(?:^|(?<=&))[^=[]+/', function($match) {
        return bin2hex(urldecode($match[0]));
    }, $data);

    parse_str($data, $values);

    return array_combine(array_map('hex2bin', array_keys($values)), $values);
}

Example usage:

$data = parse_qs($_SERVER['QUERY_STRING']);
like image 164
Amal Murali Avatar answered Sep 23 '22 19:09

Amal Murali


Quick 'n' dirty.

$str = "ProceduresCustomer.tipi_id=10&ProceduresCustomer.id=1";    

function my_func($str){
    $expl = explode("&", $str);
    foreach($expl as $r){
        $tmp = explode("=", $r);
        $out[$tmp[0]] = $tmp[1];
    }
    return $out;
}

var_dump(my_func($str));

array(2) {
    ["ProceduresCustomer.tipi_id"]=> string(2) "10"
    ["ProceduresCustomer.id"]=>string(1) "1"
}
like image 37
The Blue Dog Avatar answered Sep 22 '22 19:09

The Blue Dog