PHP explode() Function
Example
Split a string into an array by the specified delimiter .:
Run Example »
Output result:
Array
(
[0] => www
[1] => runoob
[2] => com
)
Definition and Usage
explode() is a function in PHP used to split a string into an array by a specified delimiter.
explode() is typically used to process strings containing multiple values, splitting them into an array for easier manipulation and access to each part.
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: The delimiter, specifies the character or string used to split the string. This delimiter acts as the cutting point in the string.
- $string: The original string to split.
- $limit(Optional): Specifies the maximum number of elements returned in the array. If
$limitis given, the returned array contains 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 split by the delimiter.
Technical Details
| Return Value: | Returns an array of strings. |
|---|---|
| PHP Version: | 4+ |
| Changelog: | In PHP 4.0.1, the limit parameter was added. In PHP 5.1.0, support for negative limits values was added. |
More examples
Example 1
Use the limit parameter to return some array elements:
" ; // array elements are 2 print_r ( explode ( ' , ' , $str , 2 ) ) ; print "" ; // remove the last array element print_r ( explode ( ' , ' , $str ,- 1 ) ) ; ?>
Run Example »
Output result:
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
)
;
Output:
Array
(
[0] => apple
[1] => banana
[2] => cherry,orange
)
When there is no delimiter:
Example
$str
=
"apple"
;
$arr
=
explode
(
","
,
$str
)
;
print_r
(
$arr
)
;
Output:
Array
(
[0] => apple
)
PHP String Reference Manual