Jeremy Gehrs
Jeremy Gehrs

Reputation: 433

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
)

Upvotes: 8

Views: 1759

Answers (3)

Sensei
Sensei

Reputation: 134

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

Upvotes: 5

zod
zod

Reputation: 12417

If you want to split by a char, but want to ignore that char in case it is escaped, use a lookbehind assertion.

In this example a string will be split by ":" but "\:" will be ignored:

<?php
$string='a:b:c\:d';
$array=preg_split('#(?<!\\\)\:#',$string);
print_r($array);
?>

Results into:

Array ( [0] => a [1] => b [2] => c\:d )

http://www.php.net//manual/en/function.preg-split.php

Upvotes: -1

Amal Murali
Amal Murali

Reputation: 76656

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
)

Upvotes: 7

Related Questions