LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Yep, another PHP question (File manipulation) (https://www.linuxquestions.org/questions/programming-9/yep-another-php-question-file-manipulation-118850/)

jacksmash 11-22-2003 09:51 AM

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??

hadding 11-22-2003 11:11 AM

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.

jacksmash 11-22-2003 11:12 AM

I'm simply tab delimiting my file. Is that the best way to do it?

I'm not sure what your "regex" thing means???

hadding 11-22-2003 11:39 AM

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

jacksmash 11-22-2003 11:45 AM

Ok thanks,
I'll work with that and let you know how it goes.

hadding 11-22-2003 11:50 AM

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

jacksmash 11-22-2003 01:07 PM

<started new thread>


All times are GMT -5. The time now is 06:38 PM.