Using PHP explode() to Split Strings: Syntax, Parameters, and Practical Examples
This article explains PHP's explode() function, detailing its syntax, parameters, and return value, and provides three practical code examples that demonstrate splitting strings by spaces, commas with a limit, and empty strings to obtain character arrays.
In PHP, strings are a common data type, and the explode() function can be used to split a string by a specified delimiter.
The basic syntax of explode() is:
explode(string $separator, string $string, int $limit = PHP_INT_MAX): arrayThe function accepts three parameters: $separator (the delimiter), $string (the string to split), and optional $limit (maximum number of array elements, default PHP_INT_MAX).
The function returns an array containing the substrings.
Example 1: Split a string by space
Code:
$str = "Hello World";
$result = explode(" ", $str);
print_r($result);Output:
Array
(
[0] => Hello
[1] => World
)This splits "Hello World" into ["Hello", "World"].
Example 2: Split by comma with element limit
Code:
$str = "apple,banana,orange,grape";
$result = explode(",", $str, 2);
print_r($result);Output:
Array
(
[0] => apple
[1] => banana,orange,grape
)This splits the string into two elements: ["apple", "banana,orange,grape"].
Example 3: Split by empty string (character by character)
Code:
$str = "Hello";
$result = explode("", $str);
print_r($result);Output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
)Using an empty string as the delimiter splits the string into individual characters.
Conclusion
By using explode() , you can easily split strings into arrays, which is useful for text processing, URL parsing, and more; proper use improves code efficiency and readability.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
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.