XML technologies / Regular expressions / PHP / The preg functions / preg_split

(Excerpt from "Regular expressions" by Jeffrey E. F. Friedl)

preg_split(pattern, suchstring [, limit, [ flags ]])

 

Parameters

pattern

The Pattern parameter: a regex with delimiters and optional modifiers (see The Pattern parameter).

suchstring

The text to split.

limit

Maximum number of pieces.

flags

Optional flags affecting behavior (see Options for preg_split):

PREG_SPLIT_NO_EMPTY
PREG_SPLIT_DELIM_CAPTURE
PREG_SPLIT_OFFSET_CAPTURE

Combine flags with bitwise OR, as shown under PREG_SET_ORDER ordering.

 

Return value

An array of strings.

Explanation

preg_split splits text into an array of pieces. The optional limit parameter limits their count, with the final piece receiving the entire remainder. Flags control which pieces are returned and how.

In a sense, preg_split is the opposite of preg_match_all: preg_split returns the pieces between matches: what remains after removing the regex's matches. preg_split is the regex counterpart of the simpler built-in PHP function explode.

For example, a financial site accepts space-separated ticker symbols. Separate them with explode :

$tickers = explode(' ', $input);

But users may enter multiple spaces. A better delimiter is ˹\s+˼ for preg_split:

$tickers = preg_split('/\s+/', $input);

Users also enter commas or commas with spaces, even when told otherwise, for example ›YHOO, AAPL, GOOG‹. Allow that too:

$tickers = preg_split('/[\s,]+/', $input);

Our example produces a $tickers array containing ›YHOO‹, ›AAPL‹, and ›GOOG‹.

 

Sites like Flickr categorize photos with comma-separated tags. Here, use ˹\s*,\s*˼ to permit whitespace around commas:

$tags = preg_split('/\s*,\s*/', $input);

Compare ˹\s*,\s*˼ and ˹[\s,]+˼. The first requires a comma but permits surrounding whitespace. Given $input of ›123,,,456‹, the regex matches three commas and preg_split returns four pieces: ›123‹, two empty elements, and ›456‹.

With ˹[\s,]+˼, however, $input splits at each comma, whitespace, or sequence of either. The example ›123,,,456‹ yields only ›123‹ and ›456‹.

 

The preg_split limit parameter

A limit argument ensures preg_split returns at most that many pieces. When reached, the final element contains the entire remaining subject.

Suppose we manually decode HTTP response headers. The standard separates headers and data with ›\r\n\r\n‹, but servers sometimes send only ›\n\n‹.

Using preg_split handles both. With the response in $response,

$parts = preg_split('/\r? \n \r? \n/x', $response, 2);

returns headers in $parts[0] and data in $parts[1]. (The x modifier makes the regex clearer; see Regex modes.)

The third argument, 2, limits splitting to two parts. The first match places preceding headers in element one, then stops searching and places all remaining data in element two.

Without limit (or with -1), many more pieces might be produced, likely corrupting the data.

A limit does not guarantee exactly that many elements, only no more elements, except for a situation discussed under PREG_SPLIT_DELIM_CAPTURE.

Limits help when the last element should receive the remainder, as when isolating headers without touching data. Our 2 accomplishes that.

Limits also help if not all pieces from preg_split are needed. Suppose personnel fields (first name, last name, address, age, etc.) are separated by ˹\s*,\s*˼ and only names matter. Set limit to 3 to make preg_split stop after two fields:

$felder = preg_split('/\s* , \s*/x', $personendaten, 3);

Other fields land in the third element, which can be removed with array_pop or simply ignored.

To use flags without a limit argument, supply the placeholder -1 meaning unlimited. A value of 1 means no splitting, rarely useful. Values below -1 or 0 have undefined behavior; avoid them.

 

Options for preg_split

preg_split supports three options, alone or combined by bitwise OR (see The preg_match_all PREG_OFFSET_CAPTURE flag).

PREG_SPLIT_OFFSET_CAPTURE

This has the same effect as PREG_OFFSET_CAPTURE with preg_match and preg_match_all: result elements become arrays containing offsets and substrings rather than plain strings.

PREG_SPLIT_NO_EMPTY

Suppress empty elements, also excluding them from the limit count. Empty elements arise from matches at the subject's boundaries or consecutive matches.

In the Flickr tag example, the text ›Party,,Fest‹ with the original code

$tags = preg_split('/\s* , \s*/x', $input);

returns three elements: ›Party‹, an empty element, and ›Fest‹. The empty element is the nothing between the commas.

Adding the option PREG_SPLIT_NO_EMPTY to the same example

$tags = preg_split('/\s* , \s*/x', $input, -1, PREG_SPLIT_NO_EMPTY);

yields only ›Party‹ and ›Fest‹.

PREG_SPLIT_DELIM_CAPTURE

Captured delimiter text is also added to the result. Suppose search terms are separated by ›und‹ or ›oder‹, for example:

DSLR Kamera und Nikon D200 oder Canon EOS 30D

Without PREG_SPLIT_DELIM_CAPTURE, using

$begriffe = preg_split('/\s+ (und|oder) \s+/x', $input);

produces $begriffe containing:

array ('DSLR Kamera', 'Nikon D200', 'Canon EOS 30D')

All delimiter text is gone. With PREG_SPLIT_DELIM_CAPTURE (and -1 as the placeholder for limit),

$begriffe = preg_split('/\s+ (und|oder) \s+/x', $input, -1, PREG_SPLIT_DELIM_CAPTURE);

we also get in $begriffe the captured text:

array ('DSLR Kamera', 'und', 'Nikon D200', 'oder', 'Canon EOS 30D')

One extra element per split is added because there is one capturing group. Later processing can handle ›und‹ and ›oder‹ specially.

Note that PREG_SPLIT_DELIM_CAPTURE does nothing with noncapturing parentheses (for example '/\s+(?:und|oder)\s+/'): only capturing groups count.

Revisit the ticker example:

$tickers = preg_split('/[\s,]+/', $input);

Adding captures and PREG_SPLIT_DELIM_CAPTURE means

$tickers = preg_split('/([\s,]+)/', $input, -1, PREG_SPLIT_DELIM_CAPTURE);

no original text is lost: it is simply split into the array $tickers. Odd-indexed elements then correspond to the delimiter capture, ˹([\s,]+)˼. This helps print errors with original context.

Elements produced by PREG_SPLIT_DELIM_CAPTURE do not count against an explicit limit. Results can therefore exceed the limit, greatly if the delimiter has several capturing groups.

Nonparticipating trailing captures produce no result elements. For an unmatched group (see Trailing empty match elements are omitted), an empty string may or may not be returned: it appears if a higher-numbered group actually participates; otherwise not. With PREG_SPLIT_NO_EMPTY, none of this matters because no empty elements are returned.

  

 

 

 

German edition copyright © 2008 by O’Reilly Verlag GmbH & Co. KG
You may print the online version for private use.
Otherwise, this chapter from "Reguläre Ausdrücke" is subject to the same terms as the bound edition: the work and all its parts are protected by copyright. All rights reserved, including reproduction, translation, microfilming, storage and processing in electronic systems.

O’Reilly Verlag GmbH & Co. KG, Balthasarstr. 81, 50670 Köln

back to top