Results 1 to 3 of 3

Thread: Searching text files

  1. #1
    Join Date
    May 2009
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default Searching text files

    I'm a beginner at this so I apologize in advance!

    I'm trying to search for a specific word in a text file which has lines like this:

    first sentence
    second sentence
    sentence sentence

    I only want to search for the first word of every line though, so if I search for "sentence" I only want the 3rd line to be outputted, although the first two have "sentence" in them as it's not the first word.. I'm wondering if this is possible?

    Thanks in advance.

  2. #2
    Join Date
    Mar 2007
    Location
    New York, NY
    Posts
    557
    Thanks
    8
    Thanked 66 Times in 66 Posts

    Default

    It's possible, but complex. Use explode(); to organize the lines into an array. Use foreach() statement to use strpos(); to find lines that start with the text that begins with {string}.

    Here's the code for it: {
    PHP Code:
    <?php

    $myFile 
    "testFile.txt";
    $fh fopen($myFile'r');
    $text fread($fhfilesize($myFile));
    fclose($fh);

    //the file was opened and read, now, the fun begins:

    $text "first sentence\nsecond sentence\nsentence sentence"// text to find
    $toFind "sentence"// what to search for.

    $tnt explode("\n"$text);

    foreach(
    $tnt as $txt) {

    $str strpos($text$toFind);

    if(
    $str === FALSE) {
    print 
    "text not found";
    } else {
    print 
    $txt// print the text which has the matching "sentence" in front of it.
    }

    ?>
    and of course, your text file [here named, testFile.txt] would look like this:
    Code:
    first sentence
    second sentence
    sentence sentence
    HTH
    - Josh

  3. #3
    Join Date
    May 2009
    Posts
    6
    Thanks
    3
    Thanked 0 Times in 0 Posts

    Default

    Thanks a lot for that

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
  •