Backend Development 3 min read

Using PHP split() to Split Strings with Regular Expressions

This article explains the PHP split() function, its syntax, behavior with optional limits, and provides two practical examples showing how to split colon‑separated and date strings using regular‑expression patterns, along with the resulting outputs.

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

The split() function in PHP uses a regular expression to divide a string into an array of substrings.

Signature:

array split(string $pattern, string $string[, int $limit])

The function returns an array of substrings; if $limit is set, the returned array contains at most $limit elements, with the last element holding the remainder of the original string. On failure, split() returns FALSE .

Example 1 – Splitting a colon‑separated string:

<?php
$passwd_line = "zhang:1234:1000:mo999:check";
list($user, $pass, $uid, $gid, $extra) = split(":", $passwd_line, 5);

echo $user;   // zhang

echo $pass;   // 1234

echo $uid;    // 1000

echo $gid;    // mo999

echo $extra;  // check
?>

Output:

zhang12341000mo999check

Example 2 – Splitting a date string with multiple possible delimiters:

<?php
// delimiter can be slash, dot, or hyphen
$date = "06/7/2020";
list($month, $day, $year) = split('[/.-]', $date);

echo "Month: $month; Day: $day; Year: $year<br />\n";
?>

Output:

Month: 06; Day: 7; Year: 2020<br />

Note: pattern is a regular expression, so special regex characters must be escaped if they are intended to be used as literal delimiters.

Backend DevelopmentPHPRegular Expressionsstring splittingsplit-function
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.