Using preg_split() to Split Strings with Regular Expressions in PHP
This article explains the PHP preg_split() function, its signature, parameters, return values, and provides multiple code examples demonstrating how to split strings using regular expressions, control split limits, and apply flags such as PREG_SPLIT_NO_EMPTY and PREG_SPLIT_OFFSET_CAPTURE.
preg_split() is a PHP function that splits a string by a regular expression pattern, returning an array of substrings.
Signature: array preg_split(string $pattern, string $subject, int $limit = -1, int $flags = 0)
Parameters: pattern – the regex pattern to search for; subject – the input string; limit – maximum number of splits (‑1, 0, or null means no limit); flags – bitwise combination of PREG_SPLIT_* constants such as PREG_SPLIT_NO_EMPTY, PREG_SPLIT_DELIM_CAPTURE, and PREG_SPLIT_OFFSET_CAPTURE.
Return value: an array of substrings (or arrays containing the substring and its offset when PREG_SPLIT_OFFSET_CAPTURE is used).
Example 1 splits a phrase using commas or whitespace:
Output:
Array
(
[0] => hypertext
[1] => language
[2] => programming
)Example 2 demonstrates using PREG_SPLIT_NO_EMPTY to remove empty elements:
Output shows each character as a separate element.
Example 3 shows PREG_SPLIT_OFFSET_CAPTURE to obtain substrings with their positions:
Output includes each word together with its offset in the original string.
Laravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.