I have an applications developed with PHP. I have a big text file where I want to match for a word but this can be change in the feature. How can I match a word in PHP?

Recommended Answers

All 2 Replies

I'm not sure what you mean by match a word. Do you mean tell if the word exists in the text file?

How big is the text file? Do you want to load it all into memory and then search it a bunch of times, or do you want to conserve memory and read from the file line by line, stopping if the word exists?

You can use $file = file_get_contents("path/to/file"); to load the contents of the text file into the $file variable.

You can use $lines_of_file_arr = file("path/to/file"); to load the contents of the text file into an array, with each line being an array element. You can then search the array for the specific words.

You can read a file line by line with a loop:

  $line_of_file =  fgets($file);

Within the loop, you would check to see if the line matches the word. If it does, you can break out of the while loop with break;.

Good luck!!

There are different functions and ways to match a word in PHP. Best way is using preg_match() function. In the following example we will search the forum word in the $bigtext content.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.