1.11. Taking Strings Apart
Problem
You need to break a string
into pieces. For example, you want to access each line that a user
enters in a <textarea> form field.
Solution
Use explode( )
if what separates the pieces is a
constant string:
$words = explode(' ','My sentence is not very complicated');Use split( )
or preg_split( ) if you
need a POSIX or Perl regular expression to describe the separator:
$words = split(' +','This sentence has some extra whitespace in it.');
$words = preg_split('/\d\. /','my day: 1. get up 2. get dressed 3. eat toast');
$lines = preg_split('/[\n\r]+/',$_REQUEST['textarea']);Use spliti( ) or the /i flag to
preg_split( ) for
case-insensitive separator matching:
$words = spliti(' x ','31 inches x 22 inches X 9 inches');
$words = preg_split('/ x /i','31 inches x 22 inches X 9 inches');Discussion
The simplest solution of the bunch is explode( ).
Pass it your separator string, the string to be separated, and an
optional limit on how many elements should be returned:
$dwarves = 'dopey,sleepy,happy,grumpy,sneezy,bashful,doc';
$dwarf_array = explode(',',$dwarves);Now $dwarf_array is a seven element array:
print_r($dwarf_array); Array ( [0] => dopey [1] => sleepy [2] => happy [3] => grumpy [4] => sneezy [5] => bashful [6] => doc )
If the specified limit is less than the number of possible chunks, the last chunk contains the remainder:
$dwarf_array = explode(',',$dwarves,5);
print_r($dwarf_array);
Array
(
[0] => dopey
[1] => sleepy
[2] => happy
[3] => grumpy
[4] ...