Using PHP explode() to Split Strings

This article explains PHP's explode() function, detailing its syntax, parameters, and usage through three examples that demonstrate splitting strings by spaces, commas, and limiting the number of resulting segments, while also mentioning related functions like implode and str_split.

php Courses
php Courses
php Courses
Using PHP explode() to Split Strings

In PHP programming, splitting a string into multiple substrings is common, and the built‑in explode function provides a convenient way to achieve this.

Syntax of explode()

array explode(string $delimiter, string $string [, int $limit = PHP_INT_MAX])

The $delimiter parameter specifies the character or string used to determine where the original string should be split.

The $string parameter is the input string that will be divided.

The optional $limit parameter limits the number of resulting substrings; by default it is PHP_INT_MAX, meaning no limit.

Using explode()

Example 1 – Split by space

$myString = "Hello world! Welcome to PHP.";

$subStrings = explode(" ", $myString);

foreach ($subStrings as $subString) {
    echo $subString . "<br>";
}

This code splits the string Hello world! Welcome to PHP. at each space and outputs each part using a foreach loop.

Example 2 – Split by comma

$myString = "Apple,Banana,Orange,Strawberry,Mango";

$subStrings = explode(",", $myString);

foreach ($subStrings as $subString) {
    echo $subString . "<br>";
}

The string Apple,Banana,Orange,Strawberry,Mango is divided at commas, and each fruit name is printed in turn.

Example 3 – Limit the number of splits

$myString = "One,Two,Three,Four,Five";

$subStrings = explode(",", $myString, 3);

foreach ($subStrings as $subString) {
    echo $subString . "<br>";
}

Here the string One,Two,Three,Four,Five is split by commas but only the first three substrings are returned because of the limit parameter.

Besides explode, PHP also offers other string‑handling functions such as implode and str_split, allowing developers to choose the most suitable tool for their specific needs.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

BackendTutorialstring-manipulationexplode
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

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.