Backend Development 4 min read

Using PHP preg_split() to Split Strings with Regular Expressions

This article explains the PHP preg_split() function, its syntax, parameters, flag options, and demonstrates three practical examples showing how to split strings by patterns, control the number of results, and retrieve offset information.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using PHP preg_split() to Split Strings with Regular Expressions

The preg_split() function in PHP divides a string into an array using a regular expression pattern.

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

Parameters

pattern : The regular expression used for splitting.

subject : The input string to be split.

limit : Maximum number of elements in the resulting array; -1 , 0 or null means no limit.

flags : Bitwise combination of flags such as PREG_SPLIT_NO_EMPTY (omit empty results), PREG_SPLIT_DELIM_CAPTURE (capture delimiters), and PREG_SPLIT_OFFSET_CAPTURE (include offset of each piece).

Return value

An array containing the substrings obtained after splitting the subject by the pattern.

Example 1 – Split by commas or whitespace

<?php
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
print_r($keywords);
?>

Output:

Array
(
    [0] => hypertext
    [1] => language
    [2] => programming
)

Example 2 – Split by a literal string and remove empty elements

<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>

Output:

Array
(
    [0] => s
    [1] => t
    [2] => r
    [3] => i
    [4] => n
    [5] => g
)

Example 3 – Split by spaces and capture offsets

<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>

Output (showing each substring with its offset in the original string):

Array
(
    [0] => Array
        (
            [0] => hypertext
            [1] => 0
        )
    [1] => Array
        (
            [0] => language
            [1] => 9
        )
    [2] => Array
        (
            [0] => programming
            [1] => 18
        )
)
backendphpregular expressionsString Manipulationphp-functionspreg_split
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.