0

I'm simply looking to take the first csv out of a string, using PHP. Here are a few examples:

  • "Sea Bass, Floured Or Breaded, Fried" => "Floured Or Breaded, Fried"
  • "Tuna, Fresh, Baked Or Broiled" => "Fresh, Baked Or Broiled"
  • "Croaker, Breaded Or Battered, Baked" => "Breaded Or Battered, Baked"

And so on...

Thank you.

Yaaqov
  • 305
  • 1
  • 4
  • 14
  • Do you already have code that loads the CSV file into memory? If so, would you please post the relevant portion? – Ben Gribaudo Jul 05 '10 at 16:13
  • Show the CSV data, because what this is, isn't separating the two elements, which means you want to modify data inside a csv element rather than remove an element. – Incognito Jul 05 '10 at 16:15
  • As Ben says, how are you populating your string.... if it is from a file, then PHP's fgetcsv() function can simplify things for you – Mark Baker Jul 05 '10 at 16:21
  • Sorry but can you give more information, not sure what you mean. – PHPology Jul 05 '10 at 16:12

2 Answers2

2

You can try this:

$csvArray = explode(",", $csv);
array_shift($csvArray);
$newCsv = implode(",", $csvArray);
xil3
  • 16,062
  • 8
  • 58
  • 95
  • 1
    You don't need to (and *should not ever*) pass an array (or anything, really) by reference to a *built-in* function unless the function expressly requests a reference. Besides being [counter-intuitively slow](http://stackoverflow.com/questions/3117604/why-is-calling-a-function-such-as-strlen-count-etc-on-a-referenced-value-so-sl), it's previously been a [security risk](http://php-security.org/category/vulnerabilities/index.html) in the PHP core (check out the "interruption" bugs...) – Charles Jul 05 '10 at 16:17
  • Won't work if any of the values actually contain a comma, whereas the built in CSV handling functions can handle this – Mark Baker Jul 05 '10 at 16:21
  • array_shift does request a reference. – xil3 Jul 05 '10 at 16:21
  • @Mark Baker: yea true, but that was just a quick solution based on examples he posted. – xil3 Jul 05 '10 at 16:22
  • `array_shift` works with a reference, but you do not need to expressly create a reference to make it work. What you'd done is called "call-time pass-by-reference", and is considered such a bad practice that they added an error message just to tell people to stop doing it. – Charles Jul 05 '10 at 16:54
  • Yeah, I did notice the error message, which is why I removed it. Thanks for the heads up, though. – xil3 Jul 05 '10 at 18:09
1

I suggest using str_getcsv or something similar that parses csv, this will take into account any quotation marks and commas in the CSV string. after that you can just array_shift

Not Available
  • 2,875
  • 7
  • 25
  • 31