JeffVader
JeffVader

Reputation: 702

replacing values in a file and saving

I've got this bit of code which reads a file in, then goes through it line by line.

If there is a match in the line a value is updated :

$filePath = $_REQUEST['fn'];
$lines = file(); 
foreach ($lines as $line_num => $line) 
{
if(stristr($line,'Device') && stristr($line,'A=0FEDFA')) $line = str_replace ("ID=\"", "ID=\"***",$line);

if(stristr($line,'Style')) $line =  str_replace ("ID=\"", "ID=\"***",$line);
}

The how do I save this back as $filePath ?

Thanks

Upvotes: 0

Views: 132

Answers (2)

JeffVader
JeffVader

Reputation: 702

I've got this working doing this in PHP4 :

foreach ($lines as $line_num => $line) 
{
if(stristr($line,'Device') && stristr($line,'A=0FEDFA')) $line[$line_num] = str_replace ("ID=\"", "ID=\"***",$line);

if(stristr($line,'Style')) $lines[$line_num] =  str_replace ("ID=\"", "ID=\"***",$line);
}

then using :

fileputcontents($filePath, ("\n", $lines))

and this function for PHP4

function fileputcontents($filename, $data)
{
 if( $file = fopen($filename, 'w') )
  {
  $bytes = fwrite($file, is_array($data) ? implode('', $data) : $data);
  fclose($file); return $bytes; // return the number of bytes written to the file
  }
}

All seems to be working :)

Upvotes: 1

Michael Reed
Michael Reed

Reputation: 2382

Try this:

change:

foreach ($lines as $line_num => $line) 

to

foreach ($lines as $line_num => &$line) 

Note the & - to assign $line by reference. The changes you make to $line will then be reflected in the array containing them ($lines)

file_put_contents($filePath, implode("\n", $lines))

That line writes the altered content of the $lines array back into your file path- concatenating the elements of the array with newlines.

Upvotes: 1

Related Questions