SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Feb 2012
    Posts
    1
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    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\n";
    $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

  2. #2
    Theoretical Physics Student bronze trophy Jake Arkinstall's Avatar
    Join Date
    May 2006
    Location
    Lancaster University, UK
    Posts
    7,062
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    You need to replace in the foreach or it's only going to replace the latest line.

    PHP Code:
    $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("\n"$Lines);
    file_put_contents("ping.txt"$NewContent); 
    Jake Arkinstall
    "Sometimes you don't need to reinvent the wheel;
    Sometimes its enough to make that wheel more rounded"-Molona


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •