Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

preg_split

Splits a string by a regular expression.

Syntax

preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array|false

Parameters

ParameterTypeDescription
$patternstringThe separator pattern.
$subjectstringThe source string.
$limitintOptional. The maximum number of pieces.
$flagsintOptional. `PREG_SPLIT_NO_EMPTY` drops empty pieces.

Return value

array|falseAn array of the pieces.

Examples

Several different separators:

<?php
 
echo implode(' | ', preg_split('/[,;]\s*/', 'tea, coffee; juice'));

Output:

tea | coffee | juice

The words of a text with any number of spaces:

<?php
 
$words = preg_split('/\s+/', '  one   two three ', -1, PREG_SPLIT_NO_EMPTY);
 
echo count($words);

Output:

3

Notes

If there is a single fixed separator, use explode().

See also

  • explode — Splits a string into an array by a separator.
  • preg_match_all — Finds every match of a regular expression.

In the tutorial

  • Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.

Thanks for reading!

Donate to the site — we work hard for you.