Mitch Mitch - 10 days ago 8
PHP Question

Split URI query string like they are filters ?title=php_filter&size>2&author!=smith

My google-fu is failing me today. I'm looking to parse a query sting like:

https://example.com/some/path/here?title=my_title&size>2&author!=smith


I'm looking to the parse the query string into:

array(3) {
["title"]=>
array(2) {
["operator"]=>
string(1) "="
["search"]=>
string(8) "my_title"
}
["size"]=>
array(2) {
["operator"]=>
string(1) ">"
["search"]=>
string(1) "2"
}
["author"]=>
array(2) {
["operator"]=>
string(2) "!="
["search"]=>
string(5) "smith"
}
}


The possible operators are mostly the standard php ones: ==, !=, <>, >, <, >=, <=

Any pointers on parsing this? Thanks.

Edit 1: Thanks Armin Sam. My original URL needed a urldecode tossed in there, but otherwise, it's working fine.

function parseURLAsFilters($url) {
$url = urldecode($url);
$result = [];
$queries = explode('&', parse_url($url, PHP_URL_QUERY));
$pattern = '/(==|=|>=|<=|<>|<|>|!=)/';

foreach ($queries as $query) {
$queryArray = preg_split($pattern, $query, -1, PREG_SPLIT_DELIM_CAPTURE);
$result[$queryArray[0]] = [
'operator' => $queryArray[1],
'search' => $queryArray[2]
];
}

return $result;
}


PS: I tried to up vote your answer, but i'm not ranked high enough for the score to take effect.

Answer

I wrote a function that might get you the result you're looking for. I haven't tested it, so there might be some small issues which I'm sure you can fix.

function parseUrl($url) {
    $result = [];
    $queries = explode('&', parse_url($url, PHP_URL_QUERY));
    $pattern = '/(==|=|>=|<=|<>|<|>|!=)/';

    foreach ($queries as $query) {
        $queryArray = preg_split($pattern, $query, -1, PREG_SPLIT_DELIM_CAPTURE);
        $result[$queryArray[0]] = [
            'operator' => $queryArray[1],
            'search' => $queryArray[2]
        ];
    }

    return $result; 
}
Comments