HomeMenu
Jesus · Bible · HTML · CSS · JS · PHP · SVG · Applications

preg_split

Description

The preg_split of PCRE for PHP split string by a regular expression.

Syntax

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

Parameters

pattern

The pattern to search for, as a string.

subject

The input string.

limit

If specified, then only substrings up to limit are returned with the rest of the string being placed in the last substring. A limit of -1 or 0 means "no limit".

flags

flags can be any combination of the following flags (combined with the | bitwise operator):

ContantDescription
PREG_SPLIT_NO_EMPTYOnly non-empty pieces will be returned.
PREG_SPLIT_DELIM_CAPTUREParenthesized expression in the delimiter pattern will be captured and returned as well.
PREG_SPLIT_OFFSET_CAPTUREFor every occurring match the appendant string offset will also be returned. Note that 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

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

Examples

1 · pattern subject

<?

$pattern = "#(,\s)+#";
$subject = "coding, programming, scripting, ";

$return = preg_split($pattern, $subject);

print_r($return);
Array
(
    [0] => coding
    [1] => programming
    [2] => scripting
    [3] => 
)

2 · limit

<?

$pattern = "#(,\s)+#";
$subject = "coding, programming, scripting, ";
$limit = 2;

$return = preg_split($pattern, $subject, $limit);

print_r($return);
Array
(
    [0] => coding
    [1] => programming, scripting, 
)

3 · flags · PREG_SPLIT_NO_EMPTY

<?

$pattern = "#(,\s)+#";
$subject = "coding, programming, scripting, ";
$limit = -1;
$flags = PREG_SPLIT_NO_EMPTY;

$return = preg_split($pattern, $subject, $limit, $flags);

print_r($return);
Array
(
    [0] => coding
    [1] => programming
    [2] => scripting
)

4 · flags · PREG_SPLIT_DELIM_CAPTURE

<?

$pattern = "#(,\s)+#";
$subject = "coding, programming, scripting, ";
$limit = -1;
$flags = PREG_SPLIT_DELIM_CAPTURE;

$return = preg_split($pattern, $subject, $limit, $flags);

print_r($return);
Array
(
    [0] => coding
    [1] => , 
    [2] => programming
    [3] => , 
    [4] => scripting
    [5] => , 
    [6] => 
)

5 · flags · PREG_SPLIT_OFFSET_CAPTURE

<?

$pattern = "#(,\s)+#";
$subject = "coding, programming, scripting, ";
$limit = -1;
$flags = PREG_SPLIT_OFFSET_CAPTURE;

$return = preg_split($pattern, $subject, $limit, $flags);

print_r($return);
Array
(
    [0] => Array
        (
            [0] => coding
            [1] => 0
        )

    [1] => Array
        (
            [0] => programming
            [1] => 8
        )

    [2] => Array
        (
            [0] => scripting
            [1] => 21
        )

    [3] => Array
        (
            [0] => 
            [1] => 32
        )

)