Easy Tutorial
❮ Func Array Natsort Func Mysqli Close ❯

PHP preg_split() Function

PHP Regular Expressions (PCRE)

The preg_split function splits a string by a regular expression.

Syntax

array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

Splits the given string by a regular expression.

Parameter Descriptions:

Return Value

Returns an array of substrings from the subject that are delimited by the pattern.

Examples

Splitting a Search String

<?php
// Split the phrase by comma or whitespace (including " ", \r, \t, \n, \f)
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>

Execution result is as follows:

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

Splitting a String into Its Characters

<?php
$str = 'tutorialpro';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

Execution result is as follows:

Array
(
    [0] => t
    [1] => u
    [2] => t
    [3] => o
    [4] => r
    [5] => i
    [6] => a
    [7] => l
    [8] => p
    [9] => r
    [10] => o
)

Splitting a String and Getting the Offset of Each Part

<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

Execution result is as follows:

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

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

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

PHP Regular Expressions (PCRE)

❮ Func Array Natsort Func Mysqli Close ❯