仅替换2个其他PHP之间存在的字符串中的字符

I have an array of data in PHP about people where each line contains a string of details about that individual.

[0] => name1,email1,year1,"country1a,country1b",date1
[1] => name2,email2,year2,"country2a,country2b,country2c",date2
.... etc

The problem I am having is that I need to explode each line by commas into a multi-d array for the way I am going to process it, and that "country,country" section is messing things up because they need to be exploded as 1 item. The formatting is identical between each line, but the number of countries can vary.

I am trying to replace only those commas between the "" with another delimiter | so that I can explode them by that later.

I've tried several different strnpos and str_replace and from my searching I think preg_replace is going to be the best option but I'm having a really hard time with the regex syntax. strnpos and str_replace don't seem very efficient with having to keep track of so many different string positions at once--this is the way I tried originally with finding the positions of the ""s. It seems like this should be a simple thing to do but it hasn't been turning out that way. Can someone help me out?

Found an answer today on the 4th day of searching! It had never come up in my results before.

https://answers.yahoo.com/question/index?qid=20110425205225AAVdOh1 This answer worked perfectly when implemented as such:

foreach($tblArray as &$str) {
  $pattern = '/".+"/i';
  preg_match($pattern,$str,$matches);
  $orig = $matches[0];
  $edited = str_replace(', ','|',$orig);
  //also removed the ""s for future processing's sake
  $edited = str_replace('"',"",$edited);
  $str = str_replace($orig,$edited,$str);
}

It's pretty simple although I hadn't been thinking about a more 2-step process like this previously. I end up with

[0] => name1,email1,year1,country1a|country1b,date1
[1] => name2,email2,year2,country2a|country2b|country2c,date2

What you have is a bit of an XY problem. You want to split the items in a line, but to do that you're trying to replace the commas in quotes so that they don't interfere with the commas that separate values.

Take a step back, and try:

preg_match_all('/("[^"]+"|[^,]+),?/',$line,$matches);
$result = $matches[1];

This should give you an array containing the items, which will either be comma-separated or delimited by quotes. The ,? at the end just makes sure that the commas are consumed and not matched.

Try this:

foreach($array as &$value)if(strpos($value,',')!==false)$value=explode(',',$value);

I made this out of memory, it might not work.

(?=(?:[^"]*(?:"[^"]*"))*[^"]*$),

this will do what you want.See demo.

http://regex101.com/r/lB2sH2/3