Backend Development 3 min read

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()

<code>array explode(string $delimiter, string $string [, int $limit = PHP_INT_MAX])</code>

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

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

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

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

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

<code>$myString = "Apple,Banana,Orange,Strawberry,Mango";

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

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

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

<code>$myString = "One,Two,Three,Four,Five";

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

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

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.

BackendPHPtutorialstring-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

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.