find and replace values in csv using PHP

Posted by peirix on Stack Overflow See other posts from Stack Overflow or by peirix
Published on 2010-05-31T14:12:06Z Indexed on 2010/05/31 14:23 UTC
Read the original article Hit count: 182

Filed under:
|

I'd think there was a question on this already, but I can't find one. Maybe the solution is too easy... Anyway, I have a csv and want to let the user change the values based on a name. I've already sorted out creating new name+value-pairs using the fopen('a') mode, using jQuery to send the AJAX call with newValue and newName. But say the content looks like this:

host|http:www.stackoverflow.com
folder|/questions/
folder2|/users/

And now I want to change the folder value. So I'll send in folder as oldName and /tags/ as newValue. What's the best way to overwrite the value? The order in the list doesn't matter, and the name will always be on the left, followed by a |(pipe), the value and then a new-line.

My first thought was to read the list, store it in an array, search all the [0]'s for oldName, then change the [1] that belongs to it, and then write it back to a file. But I feel there is a better way around this? Any ideas? Maybe regex?

© Stack Overflow or respective owner

Related posts about php

Related posts about file