Forum Moderators: coopster

Message Too Old, No Replies

Removing a variable from text file

         

IamStang

3:59 am on Apr 2, 2005 (gmt 0)

10+ Year Member



Hello again!

Another NooB question.

Before I ask it. Let me just say that I am not looking for someone to write the code for me. I just need pointed in the right direction. I learn better if I do it myself. So, try not to be too specific.

On to the problem I am having. I have a txt file that reads like:

var1,var2,var3,var4,var5

Now what I need to do is comletely remove a var from the list. The var in question is submitted through a form and can be any of the vars listed.

I tried using preg_replace to no avail. It seems that using this method will not remove the delimeters (,) and leaves a blank variable in the file (var2,,var4). I need to replace (,var3,) with (,). Make sense?

If anyone cares to push me in the right direction, I would be very appreciative.

Thanks!
IamStang

IamStang

4:18 am on Apr 2, 2005 (gmt 0)

10+ Year Member



As usual!

No sooner than I give up and ask for help, I find the answer to my problem. str_replace!

Delete this post if ya want to mods.

jatar_k

4:33 am on Apr 2, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



you could also use the original preg_replace and the use str_replace to replace ,, with ,

it all depends on whether the pattern works better with preg or str

IamStang

5:20 am on Apr 2, 2005 (gmt 0)

10+ Year Member



Good suggestion!

After thinking about it for a bit, it would seem that if I just str_replaced ",var?", the script would not find and replace the first var, as it has no comma in front of it. And moving the comma to the end wouldnt help either as the last var is not followed by a comma.

Therefore, using a preg_replace for "var?" followed by a str_replace of ",," should take care of the problem.

I am sure there is probably a shorter method out there but this will suffice.

Thanks for the suggestion!
IamStang

coopster

11:15 am on Apr 2, 2005 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



A regular expression can be developed that will find the var optionally followed by a comma. A Conditional subpattern [php.net] of sorts.