Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

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] ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata