Possible Duplicate:
Split string by delimiter, but not if it is escaped
I have a string generated form ibm informix database which is separated by pipe |
characters and there are some data errors, which means there are backslash + pipe inside the data. I want to split these strings only from the pipe sign, not from backslash + pipe \|
or other signs with the pipe.
This is my code, but it works only for the pipe character:
foreach(glob("ssbstat.unl") as $file)
{
$c=0;
if(($load = fopen($file, "r")) !== false)
{
$line = fgets($load);
$count= count(explode('|', $line));
echo $fm= str_repeat('%[^|]|', $count)."%s\n";
do
{
echo $line;
print_r($line);
if($c++>10) break;
} while ($line = fscanf($load, $fm));
}
}
Can anyone help me do this?
You can do this with preg_split
. This piece [^\\\\]
specifies that pipes with backslashes should be ignored (the four backslashes are required for proper escaping. You can add any other character you want to ignore inside the []
.
print_r(preg_split('/(?<![\\\\])\|/', 'This\|is a|test|string'));