0

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

JeffVader
  • 702
  • 2
  • 17
  • 33
  • use fwrite() for write string in file try this link http://stackoverflow.com/questions/235604/overwrite-line-in-file-with-php – Rakesh Sharma Jan 24 '13 at 12:49

2 Answers2

1

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.

Michael Reed
  • 2,362
  • 23
  • 15
  • You don't need to do the `implode` in this case, since the array was built using `file`. `file_put_contents` will implode an array (without a glue) if one is passed as the data parameter, and the array will already have newline characters present since `file` leaves them intact in the array elements. – AgentConundrum Jan 24 '13 at 13:01
  • Cool. Thanks for setting me straight on that. I was PHPing from memory. – Michael Reed Jan 24 '13 at 13:02
  • No problem. I had to double-check to be sure myself. – AgentConundrum Jan 24 '13 at 13:02
  • foreach ($lines as $line_num => &$line) gives an error "Parse error: parse error, unexpected '&', expecting T_VARIABLE or '$' in " I'm running PHP4. – JeffVader Jan 24 '13 at 13:24
  • Ahhh... I see you got it working by updating the array with $lines[$line_num] rather than the reference. Good deal. – Michael Reed Jan 24 '13 at 15:27
1

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 :)

JeffVader
  • 702
  • 2
  • 17
  • 33