PHP Function Reference

PHP preg_split() Function



The PHP preg_split() function splits the given string by a regular expression.

Syntax

preg_split(pattern, subject, limit, flags)

Parameters

pattern Required. Specify the pattern to search for, as a string.
subject Required. Specify the input string.
limit Optional. If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. Default is -1 or 0 means "no limit".
flags Optional. It can be any combination of the following flags (combined with the | bitwise operator):
  • PREG_SPLIT_NO_EMPTY - If this flag is set, only non-empty pieces will be returned.
  • PREG_SPLIT_DELIM_CAPTURE - If this flag is set, parenthesized expression in the delimiter pattern will be captured and returned as well.
  • PREG_SPLIT_OFFSET_CAPTURE - If this flag is set, for every occurring match the appendant string offset will also be returned. This changes the return value in an array where every element is an array consisting of the matched string at offset 0 and its string offset into subject at offset 1.

Return Value

Returns an array containing substrings of subject split along boundaries matched by pattern, or false on failure.

Example: splitting into substrings

The example below illustrates on using this function to split a string by whitespace or comma (,).

<?php
$str = "hypertext language, programming";

//splitting by commas or space characters 
//which include " ", \r, \t, \n and \f
$keywords = preg_split("/[\s,]+/", $str);

//displaying the result
print_r($keywords);
?>

The output of the above code will be:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

Example: splitting into characters

Consider the example below which shows how to use this function to split a given string into component characters.

<?php
$str = "Programming";

//splitting into component characters
$chars = preg_split('//', $str, -1, 
                    PREG_SPLIT_NO_EMPTY);

//displaying the result
print_r($chars);
?>

The output of the above code will be:

Array
(
    [0] => P
    [1] => r
    [2] => o
    [3] => g
    [4] => r
    [5] => a
    [6] => m
    [7] => m
    [8] => i
    [9] => n
    [10] => g
)

Example: splitting a string into matches and their offsets

By using PREG_SPLIT_OFFSET_CAPTURE flag, we can capture the match offset. Consider the example below:

<?php
$str = "hypertext language programming";

//splitting by space character
$chars = preg_split('/ /', $str, -1, 
                    PREG_SPLIT_OFFSET_CAPTURE);

//displaying the result
print_r($chars);
?>

The output of the above code will be:

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )

    [1] => Array
        (
            [0] => language
            [1] => 10
        )

    [2] => Array
        (
            [0] => programming
            [1] => 19
        )

)

❮ PHP RegEx Reference