preg_split
Splits a string by a regular expression.
Syntax
preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array|falseParameters
| Parameter | Type | Description |
|---|---|---|
| $pattern | string | The separator pattern. |
| $subject | string | The source string. |
| $limit | int | Optional. The maximum number of pieces. |
| $flags | int | Optional. `PREG_SPLIT_NO_EMPTY` drops empty pieces. |
Return value
array|falseAn array of the pieces.
Examples
Several different separators:
<?php
echo implode(' | ', preg_split('/[,;]\s*/', 'tea, coffee; juice'));Output:
tea | coffee | juiceThe words of a text with any number of spaces:
<?php
$words = preg_split('/\s+/', ' one two three ', -1, PREG_SPLIT_NO_EMPTY);
echo count($words);Output:
3Notes
If there is a single fixed separator, use explode().
See also
- explode — Splits a string into an array by a separator.
- preg_match_all — Finds every match of a regular expression.
In the tutorial
- Regular expressions — Regular expressions in PHP — preg_match, preg_replace, preg_split, groups and the basic pattern notation.