Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

change text in middle file

Status
Not open for further replies.

jartse

Programmer
Apr 10, 2002
15
0
0
FI
how i change text in file
example:

text1.txt
**********************
jack
robin
john
michael
jenny
**********************

How i change john to joe. So i have to search john
then change it to joe and write it file text1.txt
and all other not change
 
The easiest way would be to read the date into an array using the file() function. Then find the row containing 'john' and change it 'joe. Finally write the array back. Only drawback would be that for extremely large files you might run into memory problems when trying to read all the entries to memory. But then again, if you're files really are growing out of proportions I would strongly recommend the use of a database system like MySQL. It's not a lie if YOU believe it ;-)
 
try this:

$mefile = fopen("file.txt","r");
$readin = fread($mefile,filesize("file.txt"));
fclose($mefile);

$mefile = fopen("file.txt","w");
for($i=0;$i<count($readin);$i++)
{
if($readin[$i] == &quot;john&quot;)
{
$readin[$i] = &quot;joe&quot;;
}
fwrite(&quot;$readin[$i]\n&quot;);
}
fclose($mefile);

basically, you've pulled the info out of the file, searched throughthe array element by element and found the one u want, replaced it with the string u wanted, and then over-writtern the original file with the old elements, and the new one, in order.
cheers
Siberd
mail: siberdude@ntlworld.com
ICQ: 44167565
 
Well, i dunno exactly what you are looking for, but from your example it looks like you just want to change &quot;Joh&quot; to &quot;Joe&quot;, right?

Check out the str_replace() function! It is very fast ;-)

I hope I was able to help! -gerrygerry
Go To
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top