How do I detect all the names for the field values in a URL in PHP? Is there a function to take all of the strings that come between the "?" and the "=" in a URL or is there a simpler way?

Dani AI

Generated

Short answer: use PHP's built-ins instead of regex. For the current request the simplest approach is to inspect the GET array; for an arbitrary URL string use parse_url() to get the query part and parse_str() to turn it into an array, then read the keys.

Example (parsing any URL):

$query = parse_url($url, PHP_URL_QUERY);
parse_str($query, $params);   // second arg returns an array safely
$keys = array_keys($params);

For the current request you can just get the keys from the incoming data:

$keys = array_keys($_GET);

Why this is better than regex or naive substring parsing: built-in parsers handle percent-encoding, PHP-style bracketed names (like field[] -> arrays), duplicate names, and fragments correctly. Regex or manual substring logic easily breaks on encoded characters, missing query parts, or unusual ordering.

Security and validation notes: don’t trust raw input. Use parse_str() with the second parameter (to avoid creating variables), then validate/filter the resulting values (for example with filter_var_array() or filter_input_array()) before using them. For AJAX you usually don’t need to discover keys server-side if the client can collect and send them reliably — use FormData or URLSearchParams on the client and let PHP receive a clean POST/GET payload.

Relevant docs:

Context from the thread: was right to point at the request arrays; ’s JS idea is workable but use URLSearchParams rather than manual substrings; ’s preg-based solution works, but the built-ins are more robust and future-proof.

Recommended Answers

All 5 Replies

check out the contents of the $_GET or $_POST variables.

But what if I don't know the contents of the $_GET and $_POST variables?

Member Avatar for Member #334542
$_GET['id']

This is the method to get the value of the field. But if you want to know exactly what is there, you should write a javascript code to fetch the url and extract the strings after ? using substring functions. Then you come to know what there present without using $_GET.

But what is the purpose?

I'm trying to write AJAX code that will pass all the valid inputs to a PHP page. Of course I'm trying to make the code re-usable. So substring functions are exactly what I'm looking for. I was told that "preg_match" might work. So right now, I'm wondering what the correct regular expression would be.

I was able to answer my own question. I used preg_match_all() to create an array containing all the keys passed in the array.
I used a regular expression to find all the strings between a "&" and "=" after the "?".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.