PHP string to array

Home - Tutorials - Basics

This short lesson teaches you how to convert a string to array using PHP built in functions.

Tutorial info:

Name:PHP string to array
Total steps:1

Bookmark PHP string to array

Step 1 - PHP string to array conversion

PHP string to array

To split a string into parts and store the result in an array can be simply solved by using the explode() function.

The syntax:

  1. array explode ( string $delimiter , string $string [, int $limit ] )

As example let’s suppose that you want to get all elements from a comma separated string like this:

  1. item1,item2,item3,item4

In this case the PHP code to convert the string into an array looks like this:

  1. $text = ‘item1,item2,item3,item4’;
  2. $delimiter=,;
  3. $itemList = explode($delimiter, $text);

Well this is nice, but what happens if you want to get every words from this text:

  1. This is   a  demo text    with  some   additional blank   space  

If you use a simple blank space as delimiter character then your result array will contain some unwanted entries as well. To solve this problem you can prepare the text before the conversion. In this case we need to replace all spaces with a simple space. Using preg_replace you can remove the unwanted spaces with the following code:

  1. $text = preg_replace('/\s+/', ' ', $text);

Now you can process your text as this:

  1. $text = '  This is   a  demo text    with  some   additional blank   space       ';
  2. $text = trim($text);
  3. $text = preg_replace('/\s+/', ' ', $text);
  4. $delimiter = ' ';
  5. $wordList = explode($delimiter, $text);

At least we need to mention the 3rd parameter which is optional. This is the limit which is a number and controls the maximum size of the array. It means that your array will be maximum that size. Your output array will still contain the complete text, but the last items value will be the remaining part of the text. Using the example above if you write this:

  1. $wordList = explode($delimiter, $text, 3);

Then the $wordList will have only 3 elements which looks like this:

  1. array
  2.   0 => string 'This' (length=4)
  3.   1 => string 'is' (length=2)
  4.   2 => string 'an example text message' (length=23)

Tags: php string to array, string to array, convert string to array, string array conversion

PHP string to array - Table of contents
Step 1 - PHP string to array conversion

Follow phpf1 on Twitter

F1 Site Family
Java F1
JavaScript F1

Total time: 0.1493