The preg_split Function

The preg_split function splits a string into array elements using a regular expression to find delimiters. The first parameter accepts a regular expression, the second - the source string. The third optional parameter specifies the number of array elements in the final result. The fourth optional parameter specifies flags that change the function's behavior.

Syntax

phppreg_split(pattern, subject, [limit], [flags]);

Flags

Flag Constant Description
PREG_SPLIT_NO_EMPTY 1 Returns only non-empty parts after splitting.
PREG_SPLIT_DELIM_CAPTURE 2 Captures and returns parts of the match with subpatterns in the regular expression.
PREG_SPLIT_OFFSET_CAPTURE 4 For each returned part, adds its position in the source string.

Example

Let's split a string by commas:

php<?php
  $res = preg_split('/,/', 'a,b,c,d,e');
  var_dump($res);
?>

Code execution result:

php['a', 'b', 'c', 'd', 'e']

Example

Let's split a string by any whitespace characters with a limit on the number of elements:

php<?php
  $res = preg_split('/\s+/', '1 2 3 4 5', 3);
  var_dump($res);
?>

Code execution result:

php['1', '2', '3 4 5']

Example

Using the PREG_SPLIT_NO_EMPTY flag to exclude empty elements:

php<?php
  $res = preg_split('/[,\s]/', 'a,b, c, ,d', -1, PREG_SPLIT_NO_EMPTY);
  var_dump($res);
?>

Code execution result:

php['a', 'b', 'c', 'd']

See Also

  • the preg_match function,
    which performs a search by regular expression
  • the explode function,
    which splits a string by a simple delimiter