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
Category:Basics
Level:Beginner

Bookmark PHP string to array



Bookmark and Share

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:

Code:
  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:

Code:
  1. item1,item2,item3,item4

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

Code:
  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:

Code:
  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:

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

Now you can process your text as this:

Code:
  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);
  6.  

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:

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

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

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







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
AJAX F1
CSS F1
Database F1
Flash F1
HTML F1
Java F1
JavaScript F1
PhotoShop F1
PHP F1
Scripts F1
Tutorial F1
Windows F1

Total time: 0.0366