Split comma separated string into an array in PHP

PHP Coding Tips

preg_split PHP function is used to split a given string by a regular expression.

Convert ‘comma’ separated string into an array

$arr = preg_split(‘/[ ,]/’, $val_string, null, PREG_SPLIT_NO_EMPTY);

If this flag is set, only non-empty pieces will be returned by preg_split().

Example:

$val_string = “Hi\nHow, are, you”;
$arr = preg_split(‘/[,]/’, $val_string, null, PREG_SPLIT_NO_EMPTY);
print_r($arr);

Output is

Array ( [0] => Hi How [1] => are [2] => you )

Covert ‘comma’, ‘space’ or ‘new line’ string into an array

$arr = preg_split(‘/[  ,\n]/’, $val_string, null, PREG_SPLIT_NO_EMPTY);

In this example, either comma, space or new line is found, then added to array.

Example:

$val_string = “Hi\nHow, are, you”;
$arr = preg_split(‘/[ ,\n]/’, $val_string, null, PREG_SPLIT_NO_EMPTY);
print_r($arr);

All in One WordPress Hosting Starts at 30$ per month
All in One WordPress Hosting
WordPress
High optimized WordPress hosting, secure firewall, HTTPS, Backup, hack-fix guarantee and many others at 30$ per month

Output is

Array ( [0] => Hi [1] => How [2] => are [3] => you )