Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split a string on comma that is NOT followed by a space?

I want the results to be:

Cats, Felines & Cougars    
Dogs    
Snakes

This is the closest I can get.

$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = split(',[^ ]', $string);
print_r($result);

Which results in

Array
(
    [0] => Cats, Felines & Cougars
    [1] => ogs
    [2] => nakes
)
like image 368
Jeremy Gehrs Avatar asked Jun 18 '14 19:06

Jeremy Gehrs


People also ask

How do you split a string by a space and a comma?

To split a string by space or comma, pass the following regular expression to the split() method - /[, ]+/ . The method will split the string on each occurrence of a space or comma and return an array containing the substrings.

How do you split a string when there is a space?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.

How do you parse a comma separated string?

In order to parse a comma-delimited String, you can just provide a "," as a delimiter and it will return an array of String containing individual values. The split() function internally uses Java's regular expression API (java. util. regex) to do its job.

How do you split lists with commas?

Use the str. split() method to split a string by comma, e.g. my_list = my_str. split(',') .


2 Answers

You can use a negative lookahead to achieve this:

,(?!\s)

In simple English, the above regex says match all commas only if it is not followed by a space (\s).

In PHP, you can use it with preg_split(), like so:

$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = preg_split('/,(?!\s)/', $string);
print_r($result);

Output:

Array
(
    [0] => Cats, Felines & Cougars
    [1] => Dogs
    [2] => Snakes
)
like image 159
Amal Murali Avatar answered Oct 20 '22 00:10

Amal Murali


the split() function has been deprecated so I'm using preg_split instead.

Here's what you want:

$string = "Cats, Felines & Cougars,Dogs,Snakes";
$result = preg_split('/,(?! )/', $string);
print_r($result);

This uses ?! to signify that we want split on a comma only when not followed by the grouped sequence.

I linked the Perl documentation on the operator since preg_split uses Perl regular expressions:

http://perldoc.perl.org/perlre.html#Look-Around-Assertions

like image 31
Sensei Avatar answered Oct 20 '22 01:10

Sensei