Yep, another PHP question (File manipulation)
I need a tutorial or something on file manipulation. I need to be able to search for data values in a file and then overwrite them. I've been searching on php.net but have had no luck.
Any suggestions?? |
Simple search and replace:
$file = fopen($filename, 'r'); $file[$stringToMatch] = $newValue; If you want to use regex's: $file = fopen($filename, 'r'); foreach ($file as $key => $value) { if (preg_match($pattern, $key)) { $value = $newValue; } } _h What kind of data file is it. I mean what format? eg. A key data pair seperated by space on each line. |
I'm simply tab delimiting my file. Is that the best way to do it?
I'm not sure what your "regex" thing means??? |
regex == regular expressions
If its tab deleimited you'de use something like this $find = "find"; $replace = "replace"; $filename = "/path/to/your/file.txt"; if ($fd = @fopen($filename, "r+")) { $contents = ereg_replace("$find ([^\t]*)\n", "$find $replace\n", fread($fd, filesize($filename))."\n"); rewind($fd); if (!@fwrite($fd, $contents)) { echo "Error writing to file"; } fclose($fd); } else { die("Could not open $filename for reading and writing"); } Explanation: read($fd, filesize($filename))."\n"); == Read the whole file into a string & add a newline at the end ereg_replace("$find ([^\t]*)\n == search through that string for the pattern $find followed by a tab, followed by any number of caracters EXECEPT a new line, followed by a new line _h |
Ok thanks,
I'll work with that and let you know how it goes. |
Here's a search and replace class that you might want to peruse
http://www.phpguru.org/search.replace.html Blurb: "Class to enable search/replace of files. Can perform the search over one file, multiple files, entire directories with/without subdirectories. Can search using four different search functions, supporting ereg and preg regular expressions." [Edit] If you don't know much about regular expressions I'd recemmend that you get ahold of a copy of "Mastering Regular Expressions" from O'Reilly http://www.oreilly.com/catalog/regex/ It's a great book (still workin through it myself ;) ) hope this helped _h |
<started new thread>
|
All times are GMT -5. The time now is 06:38 PM. |