Table of Contents
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.
1 2 3 4 5 6 7 8 |
<?php $str = "JavaBlog, A great blog platform, and more"; $parts = explode(",", $str); print_r($parts); |
Output
1 2 3 4 5 6 7 8 |
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more ) |
Use the str_getcsv()
function
Another 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 the delimiter
argument.
So, here is a PHP script to split string by comma using the str_getcsv()
function.
1 2 3 4 5 6 7 8 |
<?php $str = "JavaBlog, A great blog platform, and more"; $parts = str_getcsv($str); print_r($parts); |
Output
1 2 3 4 5 6 7 8 |
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more ) |
Use the preg_split()
function
In 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
1 2 3 4 5 6 7 8 |
<?php $str = "JavaBlog, A great blog platform, and more"; $parts = preg_split('/,/', $str); print_r($parts); |
Output
1 2 3 4 5 6 7 8 |
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more ) |
Further reading:
Use the mb_split()
function
Here is another approach that uses regular expression. The mb_split()
function works like preg_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.
1 2 3 4 5 6 7 8 |
<?php $str = "JavaBlog, A great blog platform, and more"; $parts = mb_split(',', $str); print_r($parts); |
Output
1 2 3 4 5 6 7 8 |
Array ( [0] => JavaBlog [1] => A great blog platform [2] => and more ) |
That’s all about how to split string by comma in PHP.