How to Use preg_split in PHP: Syntax and Examples
In PHP,
preg_split splits a string into an array using a regular expression pattern as the delimiter. You provide the pattern and the string, and it returns an array of substrings separated by matches of the pattern.Syntax
The preg_split function has this syntax:
preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0): array|false
Here:
- $pattern: The regular expression pattern to split by.
- $subject: The input string to split.
- $limit: Maximum number of splits; default is no limit.
- $flags: Optional flags to modify behavior (like
PREG_SPLIT_NO_EMPTYto remove empty parts).
php
array|false preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0);
Example
This example splits a sentence into words using spaces and commas as separators.
php
<?php $text = "apple, banana orange,grape"; $parts = preg_split('/[ ,]+/', $text); print_r($parts); ?>
Output
Array
(
[0] => apple
[1] => banana
[2] => orange
[3] => grape
)
Common Pitfalls
Common mistakes include:
- Using a pattern without delimiters (like slashes
/pattern/), which causes errors. - Not escaping special regex characters in the pattern.
- Ignoring empty strings in the result when multiple delimiters appear consecutively.
Use PREG_SPLIT_NO_EMPTY flag to avoid empty parts.
php
<?php // Wrong: missing delimiters // $result = preg_split('[,]', 'a,b,c'); // Causes warning // Right: with delimiters $result = preg_split('/,/', 'a,b,c'); print_r($result); // Handling empty parts $text = 'a,,b'; // Without flag print_r(preg_split('/,/', $text)); // With flag to remove empty print_r(preg_split('/,/', $text, -1, PREG_SPLIT_NO_EMPTY)); ?>
Output
Array
(
[0] => a
[1] => b
[2] => c
)
Array
(
[0] => a
[1] =>
[2] => b
)
Array
(
[0] => a
[1] => b
)
Quick Reference
| Parameter | Description |
|---|---|
| $pattern | Regular expression pattern with delimiters to split by |
| $subject | Input string to split |
| $limit | Maximum number of splits (-1 means no limit) |
| $flags | Optional flags like PREG_SPLIT_NO_EMPTY to remove empty results |
Key Takeaways
Use
preg_split to split strings by regex patterns in PHP.Always include delimiters (like slashes) around your regex pattern.
Use
PREG_SPLIT_NO_EMPTY flag to avoid empty strings in the result.The
$limit parameter controls how many splits to perform.Check your regex pattern carefully to avoid unexpected splits.