Php 替换文件中的值并保存

Php 替换文件中的值并保存,php,replace,save,Php,Replace,Save,我有一段代码,读入一个文件,然后逐行遍历 如果行中存在匹配项,则更新值: $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(str

我有一段代码,读入一个文件,然后逐行遍历

如果行中存在匹配项,则更新值:

$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);
}
如何将其保存回$filePath

谢谢

试试这个:

更改:

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

注意&-通过引用分配$行。对$line所做的更改将反映在包含它们的数组中($line)


该行将$lines数组的修改内容写回您的文件路径中,将数组元素与换行符连接起来。

我在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);
}
然后使用:

fileputcontents($filePath, ("\n", $lines))
这个函数用于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
  }
}

一切似乎都正常:)

使用fwrite()在文件中写入字符串尝试此链接在这种情况下,您不需要执行
内爆
,因为数组是使用
文件构建的<如果将一个数组作为数据参数传递,则代码>文件\u放置\u内容
将使数组内爆(没有胶水),并且该数组将已经存在换行符,因为
文件
在数组元素中保留了完整的换行符。酷。谢谢你让我明白这一点。我是凭记忆发的。没问题。我必须仔细检查以确保我自己。foreach($line_num=>&$line)给出了一个错误“Parse error:Parse error,unexpected'&',应该是T_变量或'$”,在“我正在运行PHP4.Ahhh…”。。。我看到您通过使用$lines[$line_num]而不是引用更新数组来实现它。好交易。为下一个游荡的灵魂分享PHP4版本的投票…;)
fileputcontents($filePath, ("\n", $lines))
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
  }
}