Split String by Comma in PHP

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

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.

Output

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

Output

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.

Output

That’s all about how to split string by comma in PHP.

Was this post helpful?

Leave a Reply

Your email address will not be published. Required fields are marked *