stupid me!! replacing words and saving to file

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
Craig
Forum Commoner
Posts: 37
Joined: Thu Apr 18, 2002 3:13 pm

stupid me!! replacing words and saving to file

Post 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?
rev
Forum Commoner
Posts: 52
Joined: Wed Oct 02, 2002 3:58 pm
Location: Atlanta, GA

Post 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
Craig
Forum Commoner
Posts: 37
Joined: Thu Apr 18, 2002 3:13 pm

Post 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);
}
rev
Forum Commoner
Posts: 52
Joined: Wed Oct 02, 2002 3:58 pm
Location: Atlanta, GA

Post 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
}
?>
Craig
Forum Commoner
Posts: 37
Joined: Thu Apr 18, 2002 3:13 pm

Post by Craig »

--edit - I'm an idiot ;)
Last edited by Craig on Tue Oct 08, 2002 9:52 am, edited 1 time in total.
Craig
Forum Commoner
Posts: 37
Joined: Thu Apr 18, 2002 3:13 pm

Post by Craig »

woo hoo I got it working, thanks for your help!
rev
Forum Commoner
Posts: 52
Joined: Wed Oct 02, 2002 3:58 pm
Location: Atlanta, GA

Post by rev »

You're welcome.
Post Reply