Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a string, excluding some characters [duplicate]

Tags:

php

php4

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?

like image 817
lankitha Avatar asked Mar 20 '26 18:03

lankitha


2 Answers

Do it like this:

<?php
$line = preg_replace("/([^\\\])\|/", "$1 |", "Hi \|error\| man|ok man|perfect man");
print_r(preg_split('/[^\\\]\|/', $line));

Will output:

Array ( [0] => "Hi \|error\| man" [1] => "ok man" [2] => "perfect man" )

Testet!

Edit: Like Maerlyn said, this is also possible:

<?php
$line = "Hi \|error\| man|ok man|perfect man";
print_r(preg_split('~\\\\.(*SKIP)(*FAIL)|\|~s', $line));
like image 118
noob Avatar answered Mar 22 '26 06:03

noob


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'));
like image 32
Michael Mior Avatar answered Mar 22 '26 08:03

Michael Mior