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?
stupid me!! replacing words and saving to file
Moderator: General Moderators
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
http://www.php.net/manual/en/function.preg-replace.php
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);
}
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);
}
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
}
?>