SitePoint Sponsor

User Tag List

Results 1 to 6 of 6
  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2001
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Editing file with php

    I have one file names text.txt with some data in it

    example:

    This is first row of the file.
    This is unknown row of the file.
    This is third row of the file.

    How would I be able to edit this file and replace the word "unknown" with "second". If possible not by copying to another file, but to edit the existing one.

    Also if you know any good tutorials about "working with files with php", please post the URL.

    thanx in advance

  2. #2
    Action! filmfoto's Avatar
    Join Date
    Dec 2001
    Location
    Sweden
    Posts
    278
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    A simple script to get you started:
    PHP Code:
    <?php
    $filename 
    "text.txt";

    $fp fopen("text.txt""r");
    $contents fread($fpfilesize ($filename));
    fclose ($fp);

    $contents str_replace("unknown""second"$contents);
    echo 
    $contents;
    ?>

    Take a look at the PHP Manual:
    fopen()
    fread()
    fclose()




    Cheers.

  3. #3
    Action! filmfoto's Avatar
    Join Date
    Dec 2001
    Location
    Sweden
    Posts
    278
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Here is a modified version which also writes to a file, not just echo the content to the screen:
    PHP Code:
    <?php
    $filename 
    "text.txt";

    $fp fopen($filename"r+");
    $contents fread($fpfilesize ($filename));

    $contents str_replace("unknown""second"$contents);

    fseek($fp0);
    fwrite($fp$contents);
    fclose ($fp);
    ?>
    Hope this helps.



    Cheers.

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2001
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanx a lot to both

  5. #5
    SitePoint Enthusiast
    Join Date
    Jul 2001
    Posts
    66
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    One more thing.... How can I get "position" or "offset" of any word in my file ?

    For example how would I move a "pointer" to word that i want.

  6. #6
    Action! filmfoto's Avatar
    Join Date
    Dec 2001
    Location
    Sweden
    Posts
    278
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    That is what fseek() is for, you can read up on it here.

    This will move the file pointer x number of bytes.



    Cheers.


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
  •