8

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
)
Amal Murali
  • 70,371
  • 17
  • 120
  • 139
Jeremy Gehrs
  • 413
  • 6
  • 17

3 Answers3

5

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
)
Amal Murali
  • 70,371
  • 17
  • 120
  • 139
5

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

Sensei
  • 132
  • 5
0

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

zod
  • 11,159
  • 23
  • 64
  • 102