Как из строки сделать массив php

от admin

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.
    • $ARR = [];
    • for ($i=0; $i<strlen($STR); $i++)
    • $ARR = json_decode($STR);
    • $ARR = unserialize($STR);

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

ⓘ I have included a zip file with all the example source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

TABLE OF CONTENTS

DOWNLOAD & NOTES

First, here is the download link to the example source code as promised.

QUICK NOTES

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

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

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

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

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

Похожие статьи