Splitting a string by separators

suggest change

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 = "user@example.com";
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"

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


String parsing:
* Splitting a string by separators

Table Of Contents
2 Arrays
4 Types
10 Cookies
14 JSON
15 SOAP
17 cURL
19 XML
21 Traits
35 UTF-8
36 URLs
38 PHPDoc
40 String parsing
41 Loops
44 Closur
72 YAML
77 Cache
78 Streams
81 PDO
82 SQLite3
83 Sockets
87 MongoDB
93 IMAP
94 Redis
95 Imagick
102 APCu
108 PSR