How to Split String in PHP using Delimiter - explode() Function
PHP String FunctionsThe explode() function in PHP is used to split a string into multiple strings based on the specified delimiter. This function returns an array of strings.
Syntax
The syntax of the explode function is:
explode(string $separator, string $string, int $limit = PHP_INT_MAX)
Parameters
The $separator or delimiter is the string (can be one or more characters) used to split the $string.
The $limit is an optional parameter:
- If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.
- If the limit parameter is negative, all components except the last -limit are returned.
- If the limit parameter is zero, then this is treated as 1.
Example 1
print_r(explode(',', 'one,two,three'));
Result:
Array ( [0] => one [1] => two [2] => three )
Example 2
$var = 'Learn PHP';
print_r(explode(' ', $var));
Result:
Array ( [0] => Learn [1] => PHP )
Example 3
print_r(explode (',' ,'one,two,three', 2));
Result:
Array ( [0] => one [1] => two,three )