Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    New Coder
    Join Date
    Nov 2005
    Posts
    40
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Search a file/more efficient to use a string or array?

    Greetings,

    I'm aware PHP can read the entire contents of a file into a string then from there it's possible to search that string for some data.
    And I'm also aware that PHP can read the entire contents of a file into an array then from there it's possible to search that array for some data.

    But can PHP search a file (such as a .txt or .html file) for a string of data?
    If not, then I guess I'm stuck with the first two options I listed. In that case, lets say I have a .txt file with a bunch of text in it. I want to locate a specific phrase within that text file. Is it more efficient (faster results) to read the contents of that .txt file into a string or an array? Then perform the search.

    Thanks in advance,

    *Nick*

  • #2
    Super Moderator
    Join Date
    May 2002
    Location
    Perth Australia
    Posts
    4,048
    Thanks
    10
    Thanked 93 Times in 91 Posts
    I don't think either is that efficient, if you want to work on the file directly you would be better off using the tools available to the OS, e.g. on *NIX you could use grep via exec()

    PHP Code:
    <?php
    exec
    ("grep $searchword file.txt",$yaks);
    print_r($yaks);
    ?>
    the better solution would be to parse the text file for keywords when it is first created, store that in a DB and search the DB instead.
    resistance is...

    MVC is the current buzz in web application architectures. It comes from event-driven desktop application design and doesn't fit into web application design very well. But luckily nobody really knows what MVC means, so we can call our presentation layer separation mechanism MVC and move on. (Rasmus Lerdorf)

  • #3
    New Coder
    Join Date
    May 2006
    Posts
    15
    Thanks
    0
    Thanked 0 Times in 0 Posts
    //you can easily do it through thse functions
    $fileatt='yourfile.txt';
    $file = fopen($fileatt,'r'); //opening the file for reading
    $data = fread($file,filesize($fileatt)); // read content of file into variable $data
    fclose($file); //close file handler

    //after that you can use $data varible for searching matching string
    substr_count() function may help you see manual for more details

    enjoy......


  •  

    Posting Permissions

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