preg_split

Splits a string into an array using a regular expression as the delimiter.

Signature
preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array|false
  • Added in PHP 4.0

Parameters

ParameterTypeDescription
$patternstringThe pattern used as the delimiter, including delimiters and modifiers.
$subjectstringThe string to split.
$limitoptionalint= -1At most this many pieces; the last one holds the rest of the string. -1, 0 and null all mean no limit.
$flagsoptionalint= 0Any combination of PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE and PREG_SPLIT_OFFSET_CAPTURE.

Return value

array|falseAn array of substrings, or false on failure.

Errors

Returns false and emits an E_WARNING when the pattern fails to compile. Runtime failures also return false — check preg_last_error().

preg_split() is explode() with a pattern for a separator. Where explode() needs one fixed string, this splits on anything you can express as a regex — a comma with optional surrounding spaces, any run of whitespace, a semicolon or a newline.

When to reach for it

Use it for messy human input: tag lists typed with inconsistent spacing, lines separated by any mix of \r\n and \n, values separated by several possible characters. PREG_SPLIT_NO_EMPTY drops the empty pieces that consecutive or leading delimiters create, and PREG_SPLIT_DELIM_CAPTURE keeps the delimiters themselves in the output, which turns the function into a crude tokeniser.

What trips people up

An empty pattern '//' splits between every character, but it produces an empty string at each end and, without the u modifier, it splits bytes — so accented characters come back broken. Use '//u' with PREG_SPLIT_NO_EMPTY. A limit of 0 does not mean "nothing": it is treated as -1, unlimited. And if the separator really is a fixed string, explode() is much faster.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Turn a comma-separated tag input into an array regardless of spacing
  • Split a pasted document into lines whatever line ending it uses
  • Break a sentence into words on any run of whitespace or punctuation

Frequently asked questions

What is the difference between explode and preg_split?

explode splits on one fixed string, preg_split splits on a regular expression, so it can handle variable spacing or several alternative separators. Use explode when the separator is fixed — it is considerably faster.

How do I remove the empty strings from preg_split?

Pass PREG_SPLIT_NO_EMPTY as the fourth argument. It drops the empty pieces produced by leading, trailing or consecutive delimiters.

How do I split a string into individual characters?

Use preg_split('//u', $s, -1, PREG_SPLIT_NO_EMPTY) for UTF-8 text. For plain ASCII, str_split() is simpler and faster.

More examples

Limit and keeping the remainder

With a limit of 3 you get 'root', 'x' and the untouched remainder '0:0:root:/root'. The second call shows the trap: a limit of 0 behaves like -1 and splits everything.

Example · php
<?php
$line = 'root:x:0:0:root:/root';

print_r(preg_split('/:/', $line, 3));
print_r(preg_split('/:/', $line, 0));   // 0 means unlimited

Keeping the delimiters

With PREG_SPLIT_DELIM_CAPTURE and a capturing group around the operators, the operators appear in the output between the operands, which is enough to walk an expression. Without it, only the operands survive.

Example · php
<?php
print_r(preg_split('/([+\-*\/])/', '3+4*2', -1, PREG_SPLIT_DELIM_CAPTURE));
print_r(preg_split('/[+\-*\/]/', '3+4*2'));

Splitting multibyte text into characters

With the u modifier you get five proper characters including é. Without it the same call splits the two bytes of é apart and reports 6 pieces, several of which are invalid on their own.

Example · php
<?php
$s = 'héllo';

print_r(preg_split('//u', $s, -1, PREG_SPLIT_NO_EMPTY));
var_dump(count(preg_split('//', $s, -1, PREG_SPLIT_NO_EMPTY)));

Discussion

  • Be the first to comment on this lesson.