How to Find Words in a File Using PHP

The Hypertext PreProcessor (PHP) can search a text file to find specific words by using a combination of file reading and text searching functions. First, the file must be read, in its entirety, into a string variable and then the string variable can be searched for occurrences of the word. The script given will find the character locations of the first letters in all matching words in an array, but variations that find line numbers are possible with only minor modifications.

Instructions

    • 1

      Open a text editor such a Windows Notepad.

    • 2

      Paste the following script:

      <?php

      // Load contents of a file into a string

      $filename = "C:\something.txt";

      $handle = fopen($filename, "r");

      $contents = fread($handle, filesize($filename));

      $word = "hello";

      fclose($handle);

      // Create an array to hold all the locations of the word.

      $locations = array();

      // Find the first location.

      $pos = strpos($contents, $word, $offset);

      // Keep searching as long as you find the word.

      while ($pos !== false) {

      $locations[] = $pos;

      $offset = $pos + 1;

      $pos = strpos($contents, $word, $offset);

      }

      // Print out all the locations of the word.

      print_r($locations);

      ?>

      Replace the definition of "$word" with the word you wish to search for and the "$filename" with the name of the file you wish to search.

    • 3

      Save the script with the name "wordsearch.php."

Tips & Warnings

  • There are a number of variations on the "strpos" function that makes up the bulk of the script. The function "strrpos" will begin searching at the end of the string and go backwards. The function "stripos" will perform the search, but will not distinguish between upper and lowercase letters. The function "strripos" will begin searching from the end of the string and will not distinguish between upper and lowercase letters.

Related Searches:

References

Comments

You May Also Like

Related Ads

Featured