Hi, My file contains words like this: laugh:giggle nice:good smirk:smile I want to load the lines into an array (or 2 arrays) so that I can check through them using a 'For Each'. I basically want my script to find 'laugh' in a sentence and replace it with 'giggle', replace 'nice' with 'good' etc. Thanks.
Just use the file function which reads entire file into an array. Each element of the array corresponds to a line in the file, with the newline still attached.
Yes I get this code which reads the lines into an array: $fp = @fopen($wordsfile, 'r'); if ($fp) { $array = explode("\n", fread($fp, filesize($wordsfile))); } PHP: But I'm not to good with arrays. I could use a 'For Each' to loop through the array elements, splitting them in half. What's the best way to do this? a 2 dimentional array? Can I please have a code example? Thanks.
Try the code below and read this array tutorial. <?php $myArray = array(); $myFile = file("d:\\test.txt"); $i=0; foreach ($myFile as $line) { $myArray[$i++] = explode(':',$line); } ?> Code (markup):
Please consider some severe performance issues in the case your file is big. It would be time consumming to work with huge arrays in a server environment. If you can deal with your items one at a time, i suggest you avoid the array structure.
It's reading a file with approximately 200 lines, although this may increase up to an absolute maximum of 800 lines in future. And each line has a maximum of 10 words or so.
Don't use foreach() to replace the words then. Because it'll be applying the same replace function 800 times on the same text, which is an overkill. It'd be better to do something like: $myFile = file("d:\\test.txt"); $find = array(); $replace = array(); foreach ($myFile as $line) { $data = explode(':', trim($line)); $find[] = $data[0]; $replace[] = $data[1]; } $text = str_replace($find, $replace, $text); PHP: And if you need to apply the same function on several pieces of text, make a function of this and make sure the array is static, so you don't have to load it over and over again.
Being extreme: 10 words of 10 letters each, for 800 lines, for 1000 simultaneous users is 76 Mb. This is quite large, most of all if you are in shared hosting. Can you avoid it?
This particular function won't execute whenever the script is run. It's only ever run once for each page. The data is stored from that point on and eventually the function will never run. I'll see if this causes any problems though as a search engine spidering the site would trigger off this function quite a few times. As it stands though, the file is 200 lines long and most lines consist of under 10-20 characters. 800 lines would be an absolute maximum and it's unlikely ever to increase past 400.