php parse query string
Parse query string into an array
How can I turn a string below into an array?
This is the array I am looking for,
11 Answers 11
You want the parse_str function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
Sometimes parse_str() alone is note accurate, it could display for example:
parse_str() would return:
It would be better to combine parse_str() with parse_url() like so:
If you’re having a problem converting a query string to an array because of encoded ampersands
then be sure to use html_entity_decode
Attention, it’s usage is:
Please note that the above only applies to PHP version 5.3 and earlier. Call-time pass-by-reference has been removed in PHP 5.4
There are several possible methods, but for you, there is already a builtin parse_str function
This is one-liner for parsing query from current URL into array:
You can use the PHP string function parse_str() followed by foreach loop.
You can try this code :
This is the PHP code to split query in mysql & mssql
Query before
select xx from xx select xx,(select xx) from xx where y=’ cc’ select xx from xx left join ( select xx) where (select top 1 xxx from xxx) oder by xxx desc «;
Query after
select xx,(select xx) from xx where y=’ cc’
select xx from xx left join (select xx) where (select top 1 xxx from xxx) oder by xxx desc
Thank you, from Indonesia Sentrapedagang.com
For this specific question the chosen answer is correct but if there is a redundant parameter—like an extra «e»—in the URL the function will silently fail without an error or exception being thrown:
So I prefer using my own parser like so:
Now you have all the occurrences of each parameter in its own array, you can always merge them into one array if you want to.
parse_str
(PHP 4, PHP 5, PHP 7, PHP 8)
parse_str — Разбирает строку в переменные
Описание
Список параметров
Использовать эту функцию без параметра result крайне НЕ РЕКОМЕНДУЕТСЯ. Подобное использование объявлено УСТАРЕВШИМ с PHP 7.2.
Возвращаемые значения
Функция не возвращает значения после выполнения.
Список изменений
Примеры
Пример #1 Использование parse_str()
Пример #2 Соотношение имён parse_str()
Примечания
Смотрите также
User Contributed Notes 31 notes
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
# silently fails to handle multiple values
parse_str ( ‘foo=1&foo=2&foo=3’ );
# the above produces:
$foo = array( ‘foo’ => ‘3’ );
?>
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
# bizarre php-specific behavior
parse_str ( ‘foo[]=1&foo[]=2&foo[]=3’ );
if you need custom arg separator, you can use this function. it returns parsed query as associative array.
You may want to parse the query string into an array.
As of PHP 5, you can do the exact opposite with http_build_query(). Just remember to use the optional array output parameter.
This is a very useful combination if you want to re-use a search string url, but also slightly modify it:
Results in:
url1: action=search&interest[]=sports&interest[]=music&sort=id
url2: action=search&interest[0]=sports&interest[1]=music&sort=interest
(Array indexes are automatically created.)
CONVERT ANY FORMATTED STRING INTO VARIABLES
I developed a online payment solution for credit cards using a merchant, and this merchant returns me an answer of the state of the transaction like this:
to have all that data into variables could be fine for me! so i use str_replace(), the problem is this function recognizes each group of variables with the & character. and i have comma separated values. so i replace comma with &
Note that the characters «.» and » » (empty space) will be converted to «_». The characters «[» and «]» have special meaning: They represent arrays but there seems to be some weird behaviour, which I don’t really understand:
Here is a little function that does the opposite of the parse_str function. It will take an array and build a query string from it.
?>
Note that the function will also append the session ID to the query string if it needs to be.
The array to be populated does not need to be defined before calling the function:
Extract query string into an associative array with PHP
A little while back I posted how to extract the domain, path, etc from a url with PHP and in this follow up post show how to extract the query string into an associative array using the parse_str function.
Extract the query string with parse_url
In this example we’ll look at the URL from querying [chris hope] at Google (I don’t show up until the second page, by the way) which looks like this:
Using parse_url we can easily extract the query string like so:
The output from the above will be this:
As an aside, before continuing with using parse_str to extract the individual parts of the query string, doing print_r($parts) would show this:
Extract the query string parts with parse_str
The parse_str function takes one or two parameters (the second from PHP 4.0.3) and does not return any values. If the second parameter is present, the values from the query string are returned in that parameter as an associative array. If it is not present, they are instead set as variables in the current scope, which is not really ideal.
So, without the first parameter:
You could now echo the «q» value like this:
In my opionion, it’s better to have the values returned as an array like so:
Now doing print_r($query) would output this:
The «q» value could now be echoed like this:
Follow up posts
Have a read of my post titled «PHP: get keywords from search engine referer url» to find out how to use the parse_url function in conjunction with the parse_str function to see what query string visitors have entered into a search engine.
Get URL query string parameters
What is the «less code needed» way to get parameters from a URL query string which is formatted like the following?
Output should be: myqueryhash
I am aware of this approach:
11 Answers 11
$_SERVER[‘QUERY_STRING’] contains the data that you are looking for.
DOCUMENTATION
The PHP way to do it is using the function parse_url, which parses a URL and return its components. Including the query string.
The function parse_str() automatically reads all query parameters into an array.
EDIT
If you want the whole query string:
I will recommended best answer as
The above example will output:
This code and notation is not mine. Evan K solves a multi value same name query with a custom function 😉 is taken from:
It bears mentioning that the parse_str builtin does NOT process a query string in the CGI standard way, when it comes to duplicate fields. If multiple fields of the same name exist in a query string, every other web processing language would read them into an array, but PHP silently overwrites them:
Instead, PHP uses a non-standards compliant practice of including brackets in fieldnames to achieve the same effect.
This can be confusing for anyone who’s used to the CGI standard, so keep it in mind. As an alternative, I use a «proper» querystring parser function:
How to get parameters from a URL string?
How can I get only the email parameter from these URLs/values?
Please note that I am not getting these strings from browser address bar.
13 Answers 13
You can use the parse_url() and parse_str() for that.
will extract the emails from urls.
Use the parse_url() and parse_str() methods. parse_url() will parse a URL string into an associative array of its parts. Since you only want a single part of the URL, you can use a shortcut to return a string value with just the part you want. Next, parse_str() will create variables for each of the parameters in the query string. I don’t like polluting the current context, so providing a second parameter puts all the variables into an associative array.
As mentioned in other answer, best solution is using
parse_url()
The parse_url() parse URL and return its components that you can get query string using query key. Then you should use parse_str() that parse query string and return values into variable.
Also you can do this work using regex.
preg_match()
You can use preg_match() to get specific value of query string from URL.
preg_replace()
Also you can use preg_replace() to do this work in one line!
I created function from @Ruel answer. You can use this:
This is working great for me using php
A much more secure answer that I’m surprised is not mentioned here yet:
So in the case of the question you can use this to get an email value from the URL get parameters:
$email = filter_input( INPUT_GET, ’email’, FILTER_SANITIZE_EMAIL );
Might as well get into the habit of grabbing variables this way.