charco
charco

Reputation: 81

PHP I need to split a comma separated string into an array, BUT when the comma appear between digits ignore it

I have a string sent to php and I need to turn it into a array. In most cases there is no problem becuase the string is delimited by commas in the correct plac3es. BUT occasionally there is a comma between two digits that I need to ignore. I have tried preg_split with look behind and look forward but I always lose one of the final or beginning letters of a string.

I have been struggling with this for days. I can't use explode, or the array contains sub-strings bropken at the 1,2 commas.

For example:

bears, tigers, lions, sword-1,2-fish, penguins

I need the php to ignore the comma in sword-1,2-fish and return:

[0] ==> bears
[1] ==> tigers
[2] ==> lions
[3] ==> sword-1,2-fish
[4] ==> penguins

Anyone help, please?

Upvotes: 0

Views: 1320

Answers (2)

Robo Robok
Robo Robok

Reputation: 22755

It's perfect case to use negative lookbehind and negative lookahead:

$string = 'bears, tigers, lions, sword-1,2-fish, penguins';
$result = preg_split('#(?<!\d)\s*,\s*(?!\d)#', $string);

Upvotes: 2

charco
charco

Reputation: 81

Thanks for your contributions - I finally sorted it out using as suggested above, a lookaround.

$pattern = "/(?<=\D),(?=\D)/";                  // the expression only accepts commas that are NOT preceded by or followed by a digit (\D is NOT a digit)
$arr = preg_split($pattern, $data8);


$wrongArray="";
foreach ($arr as $wrong){
$wrongArray.="<li style='font-family:Verdana;font-size:12px;color:maroon'>".$wrong."</li>";
}

I'm going to study the other suggestions too, to see why they work. Thanks very much all.

Upvotes: 0

Related Questions