English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

PHP Basic Tutorial

PHP Advanced Tutorial

PHP & MySQL

PHP Reference Manual

PHP preg_split() Function Usage and Example

PHP Regular Expression (PCRE)

The preg_replace function splits the string using a regular expression.

Syntax

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

Split the given string using a regular expression.

Parameter description:

  • $pattern: The pattern used for searching, in string format.

  • $subject: Input string.

  • $limit: Optional. If specified, it will limit the number of substrings obtained by splitting to no more than $limit. The last substring will contain all the remaining parts. The value of limit is-1When 0 or null, it represents "unlimited". As a PHP standard, you can use null to skip the setting of flags.

  • $flags: Optional, can be any combination of the following flags (combined using bitwise OR operations |):

    • PREG_SPLIT_NO_EMPTY: If this flag is set, preg_split() will return non-empty parts after splitting.
    • PREG_SPLIT_DELIM_CAPTURE: If this flag is set, the parentheses expression in the pattern used for splitting will be captured and returned.
    • PREG_SPLIT_OFFSET_CAPTURE: If this flag is set, for each occurrence of a match, the string offset will be appended. Note: This will change each element in the returned array, making each element an array with the 0th element being the substring after the split, the1Each element is an array containing the offset of the substring in the subject.

Return value

Returns an array of substrings obtained by splitting the subject with the pattern.

Online examples

<?php
//Split phrases using commas or spaces (including " ", \r, \t, \n, \f)
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>

The execution result is as follows:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)
<?php
$str = 'w3codebox';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

The execution result is as follows:

Array
(
    [0] => r
    [1] => u
    [2] => n
    [3] => o
    [4] => o
    [5] => b
)
<?php

$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

The 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 Expression (PCRE)