Portal Home > Knowledgebase > Articles Database > Find and Replace in a file


Find and Replace in a file




Posted by Mythotical, 07-22-2009, 03:43 AM
I have been racking my head against my keyboard for nearly 2 days now. I can't figure out the problem. What I'm basically doing is opening a file for writing, using preg_replace and fwrite. There are 2 different search strings and 2 different replaces strings to go with those 2 different search strings. Here is the code: Guess I should explain the problem, when I run this it does the first one then it duplicates everything to do the second search and replace. What I want it to do is search and replace the first time then go back to the beginning and search and replace for the second one. I have tried various ways but this is becoming a big headache. Now I have asked on MyBBoard but still have yet to get a response as I put it up almost 1.5 days ago. So any help I can get to solve my problem I will be very pleased and appreciative. Cheers Last edited by Mythotical; 07-22-2009 at 03:50 AM.

Posted by foobic, 07-22-2009, 09:22 AM
The reason your second preg_replace goes back to the beginning is that you're replacing in the string $size, which is the content of the original file. It would be much easier for everyone (including you) if you were to: Use appropriate variable names (eg. $original, $modified1, $modified2)Take out the creation of your regexp pattern strings to a separate line (or in general, split up long command lines into intermediate steps where possible) For a bit more clarity the heredoc syntax can be useful to avoid all those nasty escaped quotes, although in this case you'd need to escape the $ symbols instead. Still probably worth it though. Finally, did you know the preg_replace command can also be used with arrays for pattern and replacement? Your two replacements can be done in a single command. Put it all together and I think you want something like this: It may well contain bugs - I haven't tested it - but at least set out like that you have half a chance of finding them... Last edited by foobic; 07-22-2009 at 09:26 AM.

Posted by Mythotical, 07-22-2009, 03:41 PM
Thanks so much, I'll test it out. Yeah doing my above code I'm still new to using it as I'm used to creating an automated script through an admin area then just downloading it. Knew I should have learned how to create them outside of an automated system. Again, I'll test it and I'll let you know. Thanks again.



Was this answer helpful?

Add to Favourites Add to Favourites    Print this Article Print this Article

Also Read
Amazon EC2? (Views: 717)