MOCKSTACKS
EN
Questions And Answers

More Tutorials









PHP Splitting a string


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));

Output

['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));

Output

['apple', 'pear,grapefruit,cherry']

If the limit parameter is negative, all components except the last -limit are returned.
print_r(explode(',',$fruits,-1));

Output

['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"

Conclusion

In this page (written and validated by ) you learned about PHP Splitting a string . What's Next? If you are interested in completing PHP tutorial, your next topic will be learning about: PHP Classes and Objects.



Incorrect info or code snippet? We take very seriously the accuracy of the information provided on our website. We also make sure to test all snippets and examples provided for each section. If you find any incorrect information, please send us an email about the issue: mockstacks@gmail.com.


Share On:


Mockstacks was launched to help beginners learn programming languages; the site is optimized with no Ads as, Ads might slow down the performance. We also don't track any personal information; we also don't collect any kind of data unless the user provided us a corrected information. Almost all examples have been tested. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. By using Mockstacks.com, you agree to have read and accepted our terms of use, cookies and privacy policy.