user1899415
user1899415

Reputation: 3135

php: how to cut and paste line within file

I want to search a file and make sure every row does not begin with a non-numeric character or whitespace. If it does, I want to remove line and append it to previous line (because it actually is an error with the file processing...)

Input:

29034985
491017
 Contact us at info@
19403935

Output:

29034985
491017 Contact us at info@
19403935

My code that does this:

while (($data = fgetcsv('/tmp/file.tsv', 1000, "\t")) !== FALSE) {
    if (is_numeric($data[0])){}
    else
      # do the processing here!

Any tips on how to do this? Does php have a cut/paste-like function?

Upvotes: 0

Views: 159

Answers (2)

Jithin
Jithin

Reputation: 2604

Get all content and replace using preg_replace

$data = file_get_contents('/tmp/file.tsv');
$data = preg_replace('#\n([a-zA-z].+)\n#', ' $1\n', $data);

# Write the data to a new file or to the same file

Upvotes: 1

Ashwini Agarwal
Ashwini Agarwal

Reputation: 4858

What you need to do is -

  1. Read File
  2. Process Data
  3. Write back to the file

Try this...

$counter = 0;
$csv_data = array();
while (($data = fgetcsv('/tmp/file.tsv', 1000, "\t")) !== FALSE) {
    if (is_numeric($data[0])) {
        $csv_data[$counter] = $data[0];
        $counter++;
    } else {
        $csv_data[$counter] .= ' '. $data[0];
    }
}

$fp = fopen('/tmp/file.tsv', 'w');
foreach ($csv_data as $fields) {
    fputcsv($fp, $fields);
}
fclose($fp);

Upvotes: 0

Related Questions