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:
<?php
// split by commas or whitespace
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>Output:
Array
(
[0] => hypertext
[1] => language
[2] => programming
)Example 2 demonstrates using PREG_SPLIT_NO_EMPTY to remove empty elements:
<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>Output shows each character as a separate element.
Example 3 shows PREG_SPLIT_OFFSET_CAPTURE to obtain substrings with their positions:
<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>Output includes each word together with its offset in the original string.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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.
