This article explains how to split a string by comma in PHP using different approaches.
Use the explode() function
To split string by comma, we can make use of the explode function. This function splits the string by the specified delimiter and returns an array of substrings.
Here is example of how to split string by using the explode function and specifying a comma delimiter.
Output
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more )Use the
str_getcsv()functionAnother approach is to use the
str_getcsv()function. This function parses a CSV string and returns an array of fields. By default, it uses a comma as the field delimiter, but this can be changed using thedelimiterargument.So, here is a PHP script to split string by comma using the
str_getcsv()function.Output
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more )Use the
preg_split()functionIn this approach, we can make use of regular expression. The
preg_split()function splits the string by the specified regular expression and returns an array of substrings.The function takes two arguments
- the regular expression, and
- string to be split
Here is an example on how to split string by comma in PHP using the preg_split() function
Output
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more )Further reading:
Use the
mb_split()functionHere is another approach that uses regular expression. The
mb_split()function works likepreg_split(), but it is designed to handle multi-byte character encodings.It takes two arguments;
- the delimiter, and
- the string to be split
Here is an example on how to split string by comma in PHP using the mb_split() function.
Output
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more )That's all about how to split string by comma in PHP.