webdev.gk
webdev.gk

Reputation: 219

Remove a line with specific characters in a variable before putting into CSV

I would like to ask what is the efficient way to achieve this.

I have a variable that holds the data below which is to be pass into a CSV file.

"Name","Address","Email","Comment"
", <=, ",", <=, ",", <=, ",", <=, "
"John Smith","USA","[email protected]","No Comment"

What I want to achieve is to remove the second line so that before I push the data into the CSV those characters already remove.

", <=, ",", <=, ",", <=, ",", <=, "

The only thing that I can do right now is to save the data into a file then manipulate it then use it for CSV but I am sure there is a faster way to manipulate.

Upvotes: 0

Views: 99

Answers (2)

Matt Whipple
Matt Whipple

Reputation: 7134

You could set up a small filter to automatically discard those lines as they are encountered. Something simple like:

function filtered_fputcsv($fp, $fields) {
  if ($fields ...has relevant data...) {
    fputcsv($fp, $fields);
  }
}

and use this in place of the standard writer (or a similar version for reading).

Upvotes: 1

Brad
Brad

Reputation: 163438

Your line always looks like that? As Dagon suggested:

$yourdata = str_replace('", <=, ",", <=, ",", <=, ",", <=, "', '', $yourdata);

http://php.net/manual/en/function.str-replace.php

If that junk data is always every other line, it would be much more efficient just to skip it as you re-build your data into a variable, reading line-by-line.

Upvotes: 1

Related Questions