Split comma separated string into an array in PHP

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

Output is

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

You may also like...

Thank you for visiting us. To continue receiving updates, please Subscribe to our Social Media Channels.