Replace line in txt file

hallo

i have a littleproblem with my code.
i try find a line in txt file, remove it and write new line , or just replace founding line.
this is my code:

$plik=file(“ping.txt”);
$fplik=fopen(“ping.txt”, “a+”);
$dane = (“$a $b $c $d $e $f $g”);
foreach ( $plik as $line => $value )
{
if (preg_match(‘/\b’.$a.‘\b/’, $value) ) {
echo $value;
}}
$output="$dane
";
$text = fread($fplik, filesize(“ping.txt”));
$text = str_replace($value ,$output ,$text);
fwrite($fplik,$text);
fclose($fplik);

ok and my script found line , write new line, but i cant remove old line.
i dont knew why…
pls help
thx a lot
ps:sry for my eng :slight_smile:

You need to replace in the foreach or it’s only going to replace the latest line.


$OldContent = file("ping.txt");
$Match = '/\\b' . $a . '\\b/';
$Replace = "{$a} {$b} {$c} {$d} {$e} {$f} {$g}";
$Lines = array();
foreach ($OldContent as $Line){
	if(preg_match($Match, $Line) !== false){
		$Line = $Replace;
	}
	$Lines[] = $Line;
}
$NewContent = implode("\
", $Lines);
file_put_contents("ping.txt", $NewContent);