Php query string into array

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:

http://www.google.com/search?hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=

Using parse_url we can easily extract the query string like so:

$parts = parse_url($url); echo $parts['query'];

The output from the above will be this:

hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq=

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:

Array ( [scheme] => http [host] => www.google.com [path] => /search [query] => hl=en&source=hp&q=chris+hope&btnG=Google+Search&meta=&aq=f&oq= )

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:

parse_str($parts['query'], $query);

Now doing print_r($query) would output this:

Array ( [hl] => en [source] => hp [q] => chris hope [btnG] => Google Search [meta] => [aq] => f [oq] => )

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.

Источник

Parse URL Querystring Into Array In PHP

Using query strings in PHP is a good way of transferring data from one file to another. This is done by using the $_GET variable. This variable is a global variable that is used to get the content of the query string and allow you to get at this data as an array. Getting at data in a query string can be used in other places in your application for example using Ajax requests you may need to get the contents of a query string. Here is a PHP snippet that will take a query string as a parameter and return an array of the query string data.

 /** * Parse out url query string into an associative array * * $qry can be any valid url or just the query string portion. * Will return false if no valid querystring found * * @param $qry String * @return Array */ function queryToArray($qry) < $result = array(); //string must contain at least one = and cannot be in first position if(strpos($qry,'=')) < if(strpos($qry,'?')!==false) < $q = parse_url($qry); $qry = $q['query']; >>else < return false; >foreach (explode('&', $qry) as $couple) < list ($key, $val) = explode('=', $couple); $result[$key] = $val; >return empty($result) ? false : $result; >

PHP Function parese_str

PHP has a built in function to perform this task and convert a query string into an array so that you can loop through the parameters and perform the tasks you need to. This PHP function is called parse_str(), it takes two parameters but the second is optional. The first parameter will be a string which will be the query string and the return of the function will create variables from the query string.

 $str = "first=value&arr[]=foo+bar&arr[]=baz"; parse_str($str); echo $first; // value echo $arr[0]; // foo bar echo $arr[1]; // baz

If you give this a second parameter then the return of this will add query string into an array or key value pairs.

 $str = "first=value&arr[]=foo+bar&arr[]=baz"; parse_str($str, $output); echo $output['first']; // value echo $output['arr'][0]; // foo bar echo $output['arr'][1]; // baz

Build A Query String From Array

Along with turning a query string into an array there is also a PHP function that will turn an array into a query string. This function is called http_build_query() which takes an array and will return a query string of the key value pair of the array.

 $query = array('val' => 1, 'test' => 2, 'key' => 'value'); $string = http_build_query( $query ); echo $string; // this will return val=1&test=2&key=value

Источник

Читайте также:  Html code open sans font

7 Ways To Convert String To Array In PHP

Welcome to a beginner’s tutorial on how to convert a string to an array in PHP. So you need to convert a string of data into an array before you can do your magic.

  1. $ARR = str_split($STR);
  2. $ARR = explode(«DELIMITER», $STR);
  3. $ARR = preg_split(«PATTERN», $STR);
  4. $ARR = str_word_count($STR, 2);
  5. Manually loop through the string.
  6. $ARR = [];
  7. for ($i=0; $i
  8. $ARR = json_decode($STR);
  9. $ARR = unserialize($STR);

But just how does each one of them work? Need more actual examples? Read on to find out!

TLDR – QUICK SLIDES

Convert String To Array In PHP

TABLE OF CONTENTS

ARRAY TO STRING

All right, let us now get started with the various ways to convert a string to an array in PHP.

1) SPLIT STRING

// (A) THE STRING $str = "FOOBAR"; // (B) SPLIT STRING - SPLIT ALL CHARACTERS $arr = str_split($str); print_r($arr); // F, O, O, B, A, R // (C) SET NUMBER OF CHARACTERS $arr = str_split($str, 3); print_r($arr); // FOO, BAR

This should be pretty self-explanatory. The str_split() function simply “breaks” the individual characters in a string down, and puts them into an array. Yes, we can also specify the number of characters to pull from the string.

2) EXPLODE FUNCTION

// (A) THE STRING $str = "FOO-BAR"; // (B) SPLIT BY SPECIFIED CHARACTER $arr = explode("-", $str); print_r($arr); // FOO, BAR 

The explode() function is the cousin of str_split() . But instead of breaking a string by the number of characters, it breaks the string by a given DELIMITER character (or characters).

3) PREG SPLIT

// (A) THE STRING $str = "FOO BAR, HELLO WORLD"; // (B) SPLIT BY PATTERN $arr = preg_split("/(\s|,\s)/", $str); print_r($arr); // ["FOO", "BAR", "HELLO", "WORLD"]

So what happens if we have VERY specific instructions on how to break a string? Introducing, the preg_split() function, where we can specify a custom rule on how to break the string into an array. In the above example, the /(\s|,\s)/ part is called a regular expression. In English, it reads “a white space \s , or | a comma followed by white space ,\s “.

Yep, even though the regular expression is flexible and powerful, it is also “inhuman” and difficult to understand at the same time. As it is a can of worms on its own, I will just leave a link below for those of you who want to learn more.

4) STRING WORD COUNT

// (A) THE STRING $str = "Foo Bar, hello world. Goodbye world3 = John@Doe."; // (B) STR_WORD_COUNT(STRING, FORMAT, LIST) // (B1) FORMAT 0 - RETURNS NUMBER OF VALID WORDS echo str_word_count($str, 0); // 8 // (B2) FORMAT 1 - RETURN ARRAY OF VALID WORDS $arr = str_word_count($str, 1); print_r($arr); // Foo, Bar, hello, world, Goodbye, world, John, Doe // (B3) FORMAT 2 - RETURN ARRAY OF VALID WORDS, WITH STARTING POSTION $arr = str_word_count($str, 2); print_r($arr); /* 0 - Foo, * 4 - Bar, * 9 - hello, * 15 - world, * 22 - Goodbye, * 30 - world, * 39 - John, * 44 - Doe */ // (C) 3RD PARAMETER - CHARACTERS TO CONSIDER AS "ENGLISH WORD" $arr = str_word_count($str, 2, "3@"); print_r($arr); /* 0 - Foo, * 4 - Bar, * 9 - hello, * 15 - world, * 22 - Goodbye, * 30 - world3, * 39 - John@Doe */
  • Kind of confusing, but str_word_count(STRING, MODE, LIST) takes in 3 parameters.
  • The first parameter is the STRING itself. Captain Obvious. 🙄
  • The second parameter is the important one that “changes” the MODE of the function.
    • 0 will simply count the total number of valid English words in the string. Not what we are looking for.
    • 1 will return an array of valid words in the string – Yes, this is useful if you want to filter out all the gibberish in a string.
    • 2 does the same as 1 . But the index of the array will correspond to the starting position of the word in the string.

    5) MANUAL FOR LOOP

    // (A) THE STRING $str = "FOO-BAR"; // (B) MANUAL LOOP & SPLIT $arr = []; for ($i=0; $i > print_r($arr); // F, O, O, B, A, R

    Finally, here is a “manual” alternative – We simply use a for loop to run through the characters of a string. Yep, the characters of a string act just like an array, and we can access them via STRING[N] . While this may seem to be quite a hassle, but the good part is – We can do all sorts of “special” rules and processing with this one.

    6) JSON DECODE

    // (A) JSON STRING $str = '["Red","Green","Blue"]'; // (B) JSON DECODE $arr = json_decode($str); print_r($arr); // Red, Green, Blue

    The json_decode(STRING) function takes a (previously) JSON encoded string, and turns it back into an array (or object). Yes, for you guys who have not heard, JSON stands for Javascript Object Notation. In simple terms, it’s a great way to JSON encode an array in Javascript, send it to the server, then JSON decode in PHP to get the array back.

    7) UNSERIALIZE

    // (A) SERIALIZED STRING $str = 'a:3:'; // (B) UNSERIALIZE BACK TO ARRAY $arr = unserialize($str); print_r($arr); // Red, Green, Blue

    For you guys who have not heard – Yes, we can store arrays, objects, functions, and almost anything as serialized strings in PHP using the serialize() function. To get it back, we simply use the unserialize() function.

    DOWNLOAD & NOTES

    Here is the download link to the example code, so you don’t have to copy-paste everything.

    SUPPORT

    600+ free tutorials & projects on Code Boxx and still growing. I insist on not turning Code Boxx into a «paid scripts and courses» business, so every little bit of support helps.

    EXAMPLE CODE DOWNLOAD

    Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

    That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

    SUMMARY

    • STRING is the string itself to work on…
    • FORMAT
      • 0 to return the number of words in the string.
      • 1 returns an array of words found in the string.
      • 2 to return an array of words, but the key will also mark the starting position of the word.

      TUTORIAL VIDEO

      INFOGRAPHIC CHEAT SHEET

      THE END

      Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

      Leave a Comment Cancel Reply

      Breakthrough Javascript

      Take pictures with the webcam, voice commands, video calls, GPS, NFC. Yes, all possible with Javascript — Check out Breakthrough Javascript!

      Socials

      About Me

      W.S. Toh is a senior web developer and SEO practitioner with over 20 years of experience. Graduated from the University of London. When not secretly being an evil tech ninja, he enjoys photography and working on DIY projects.

      Code Boxx participates in the eBay Partner Network, an affiliate program designed for sites to earn commission fees by linking to ebay.com. We also participate in affiliate programs with Bluehost, ShareASale, Clickbank, and other sites. We are compensated for referring traffic.

      Источник

Оцените статью