Page 1 of 1
stupid me!! replacing words and saving to file
Posted: Tue Oct 08, 2002 8:03 am
by Craig
right, my heads gone to jelly I think this should be simple but I'm in a pickle!
If I have a file and in amongst the words are words like this:
%here% ^there^ &everywhere&
and I want to open it and change each occurence of the above to
|h| |t| |e|
and then save the file, how would I go about doing that?
Posted: Tue Oct 08, 2002 8:19 am
by rev
Give preg_replace() a whirl. If it doesn't slim your fancy, then let us know.
http://www.php.net/manual/en/function.preg-replace.php
Posted: Tue Oct 08, 2002 8:27 am
by Craig
Yeah, I understand about preg-replace and str-replace already, my problem is I don't seem to have any idea on how to open a file search for the words, replace them and then save the file all I've done before is replace words as they have been inputted through a form. This time I need to change the actual file.
I thought this might be in the right direction but it's obviously incomplete...
$fp = fopen(myfile.txt, "a") or die("it's not there");
while($word = fgets($fp,4096)) {
$fp = str_replace("%here%", "[h]", $fp);
$fp = str_replace("^there^", "[t]", $fp);
$fp = str_replace("&everywhere&", "[e]", $fp);
}
Posted: Tue Oct 08, 2002 8:35 am
by rev
Oh... Does this seem reasonable?
Code: Select all
<?php
$yourFile = "/path/to/your/magic/file.txt";
/* The lovely file() function creates an array from each line in the text file */
$fileArray = file($yourFile);
/* Iterate through $fileArray */
foreach($fileArray as $eachLine) {
// do something to $eachLine
}
?>
Posted: Tue Oct 08, 2002 9:43 am
by Craig
--edit - I'm an idiot

Posted: Tue Oct 08, 2002 9:47 am
by Craig
woo hoo I got it working, thanks for your help!
Posted: Tue Oct 08, 2002 10:40 am
by rev
You're welcome.