PHP Splitting a string by separators


explode and strstr are simpler methods to get substrings by separators.

A string containing several parts of text that are separated by a common character can be split into parts with the explode function.

$fruits = "apple,pear,grapefruit,cherry";
print_r(explode(",",$fruits)); // ['apple', 'pear', 'grapefruit', 'cherry']

The method also supports a limit parameter that can be used as follow:

$fruits= 'apple,pear,grapefruit,cherry';

If the limit parameter is zero, then this is treated as 1.

print_r(explode(',',$fruits,0)); // ['apple,pear,grapefruit,cherry']

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.

print_r(explode(',',$fruits,2)); // ['apple', 'pear,grapefruit,cherry']

If the limit parameter is negative, all components except the last -limit are returned.

print_r(explode(',',$fruits,-1)); // ['apple', 'pear', 'grapefruit']

explode can be combined with list to parse a string into variables in one line:

$email = "";
list($name, $domain) = explode("@", $email);

However, make sure that the result of explode contains enough elements, or an undefined index warning would be triggered.

strstr strips away or only returns the substring before the first occurrence of the given needle.

$string = "1:23:456";
echo json_encode(explode(":", $string)); // ["1","23","456"]
var_dump(strstr($string, ":")); // string(7) ":23:456"

var_dump(strstr($string, ":", true)); // string(1) "1"