Use explosions more intelligently

I have the following line:

$string = "This is my string, that I would like to explode. But not\, this last part";

      

I want a explode(',', $string)

string, but explode()

shouldn't blow up when there is a comma in front of it \

.

Desired result:

array(2) {
  [0] => This is my string
  [1] => that I would like to explode. But not , this last part
}

      

+3


source to share


1 answer


I would use preg_split()

:

$result = preg_split('/(?<!\\\),/', $string);

print_r($result);

      



(?<!\\\\)

is lookbehind. Thus, it ,

does not precede \

. Usage is \\\

necessary to represent the only one \

as it is an escape character.

+3


source







All Articles