When posting code, please use the ‘Preformatted Text’ menu button </>.
Programming is not some random process where you keep trying different things until you eventually get one to work. It is an exact science. The computer only does exactly what your code and data tells it to do. All the php statements are documented as to what input parameters they take, what processing they do, and what value they return. The first posted code looks like a random jumble of statements that don’t have anything to do with using the php documentation. Return values are not used, return values that have a specific type are used as parameters in other functions that don’t take those type of values, multiple statements that perform the same action are being used.
Next, to produce code that does what you want, first define what inputs you have/need, what processing you are going to do on those inputs, and what result or output you are going to produce. You then break each part of the process down into the steps needed to accomplish the process, taking into account limits and extents, such as will all the data in the input file fit in memory at once… You then write, test, and debug the code for each step, before going onto the next step.
You already have a statement of the top level process, break this down into numbered steps -
- Read a file - will this data all fit into memory or will you need to loop over each line in the file?
- Replace all numbers with a #.
- Write the data to another (different) file. I’m pretty sure that everyone here thinks that writing the data to another file means it is in addition to, separate from, different from the input file.
Your 2nd posted code is much better than the 1st. It implements the steps, except that it only replaces the number ‘5’ in the data. The only complaint about the 2nd code is don’t use one letter variables. Variables should be named as to the meaning of the data in them. How about using $in_file for the input filename and $out_file for the output file name?
So, you are left with finding a way of replacing all numbers (without writing out line after line of code for each possible value.) Your course work/instructor shouldn’t have given you this assignment without first covering at least one method of accomplishing this task. However, when you were examining the documentation for str_replace(), one of the possible values for the search parameter is an array. Specifically -
If search is an array and replace is a string, then this replacement string is used for every value of search.
So, at this point you are faced with producing an array containing all the numbers (again, hopefully, without writing out all the values.) I recommend that you look at the range() function to do this part of this step.