PHP explode()Functions
Examples
Split the string by the specified delimiter.into an array:
$str = "www.example.com";
print_r (explode(".",$str));
Run example »
Output:
Array
(
[0] => www
[1] => example
[2] => com
)
Definition and Usage
explode() is a PHP function used to split a string into an array by a specified delimiter.
explode() is commonly used to process strings containing multiple values, breaking them into an array so that the individual parts can be more easily manipulated and accessed.
Note:The "separator" parameter cannot be an empty string.
Note:This function is binary-safe.
Syntax
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
Parameter description:
- $separator: Separator, specifies the character or string used to split the string. This separator will act as the cutting point in the string.
- $string: The original string to be split.
- $limit(Optional): Specifies the maximum number of elements in the returned array. If given
$limit, the returned array will contain at most$limitelements, with the last element containing all the remaining content. If not specified, the default value isPHP_INT_MAX, meaning no limit.
Return Value
Returns an array containing the parts separated by the delimiter.
Technical Details
| Return Value: | Returns an array of strings. |
|---|---|
| PHP Version: | 4+ |
| Changelog: | In PHP 4.0.1, thelimitparameter was added. In PHP 5.1.0, support for negativelimitswas added. |
More Examples
Example 1
Use the limit parameter to return some array elements:
$str = 'one,two,three,four';
//Returns an array containing one element
print_r(explode(',',$str,0));
print "<br>";
//Array has 2 elements
print_r(explode(',',$str,2));
print "<br>";
//Remove the last array element
print_r(explode(',',$str,-1));
Run example »
Output:
Array
(
[0] => one,two,three,four
)
Array
(
[0] => one
[1] => two,three,four
)
Array
(
[0] => one
[1] => two
[2] => three
)
Limit the number of returned array elements:
Example
$str = "apple,banana,cherry,orange";
$arr = explode(",", $str, 3);
print_r($arr);
$arr = explode(",", $str, 3);
print_r($arr);
Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry,orange
)
When there is no delimiter:
Example
$str = "apple";
$arr = explode(",", $str);
print_r($arr);
$arr = explode(",", $str);
print_r($arr);
Output:
Array
(
[0] => apple
)
PHP String Reference Manual Other Extensions