array explode(string $separator, string $string, int $limit = PHP_INT_MAX)
$separator : The specified delimiter (string type) is used to determine where to split the original string;
$string : The original string that needs to be split;
$limit (optional): Used to limit the number of elements returned to the array. If this parameter is set:
Be a positive number, return no more than $limit elements, and the last element will contain the remaining string;
If it is a negative number, the specified number of elements will be ignored from the end;
If 0 is returned, an empty array (starting from PHP 8.0.0).
<?php
$input = "apple,banana,orange";
$result = explode(",", $input);
print_r($result);
?>
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
This example shows how to split a comma-separated list of fruits into an array of single string items.
<?php
$input = "one|two|three|four";
$result = explode("|", $input, 3);
print_r($result);
?>
Output:
Array
(
[0] => one
[1] => two
[2] => three|four
)
Set $limit = 3 , that is, only three elements are generated at most. The third element will contain the remaining unsplit content.
Suppose you have a URL path /user/profile/settings , and you want to split it into path segments:
<?php
$url = "/user/profile/settings";
$parts = explode("/", $url);
print_r($parts);
?>
Output:
Array
(
[0] =>
[1] => user
[2] => profile
[3] => settings
)
Note: Since the path starts with a slash, the first element in the result of exploit() is an empty string.
You can use array_filter() to filter null values:
<?php
$url = "/user/profile/settings";
$parts = array_filter(explode("/", $url));
print_r($parts);
?>
If you get parameters from a query string, for example: name=John&age=30&city=Beijing , you can first use exploit() to split:
<?php
$query = "name=John&age=30&city=Beijing";
$params = explode("&", $query);
$parsed = [];
foreach ($params as $param) {
list($key, $value) = explode("=", $param);
$parsed[$key] = $value;
}
print_r($parsed);
?>
Output:
Array
(
[name] => John
[age] => 30
[city] => Beijing
)
exploit() is usually used in conjunction with functions such as trim() , array_map() . For example, when processing CSV data, you may need to clean the spaces first:
<?php
$csv = "Tom, Jerry , Spike ";
$names = array_map('trim', explode(",", $csv));
print_r($names);
?>
Output:
Array
(
[0] => Tom
[1] => Jerry
[2] => Spike
)
Parse CSV data rows
Processing combined fields read from the database
Slice logs or paths according to rules
Decompose custom configuration formats
Process URL routing
For example, in a simple routing system, we might parse the URL like this:
<?php
$request = "/article/123";
$segments = array_filter(explode("/", $request));
// gitbox.net Routing processing
if (isset($segments[0]) && $segments[0] === "article") {
$articleId = $segments[1] ?? null;
echo "You are visiting the articleIDfor $articleId Page";
}
?>