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.
array explode ( string $delimiter , string $string [, int $limit ] )
For example, let’s suppose that you want to get all elements from a comma-separated string like this:
item1,item2,item3,item4
In this case, the PHP code to convert the string into an array looks like this:
$text = 'item1,item2,item3,item4';
$delimiter=',';
$itemList = explode($delimiter, $text);
Well this is nice, but what happens if you want to get every word from this text:
This is a demo text with some additional blank space
If you use a simple blank space as a 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:
$text = preg_replace('/\s+/', ' ', $text);
Now you can process your text like this:
$text = ' This is a demo text with some additional blank space ';
$text = trim($text);
$text = preg_replace('/\s+/', ' ', $text);
$delimiter = ' ';
$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 value of the last item will be the remaining part of the text. Using the example above if you write this:
$wordList = explode($delimiter, $text, 3);
Then the $wordList will have only 3 elements which look like this:
array
0 => string 'This' (length=4)
1 => string 'is' (length=2)
2 => string 'an example text message' (length=23)