Log in

View Full Version : Searching text files



rachelk
07-31-2009, 05:21 AM
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.

JShor
07-31-2009, 02:52 PM
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

$myFile = "testFile.txt";
$fh = fopen($myFile, 'r');
$text = fread($fh, filesize($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:


first sentence
second sentence
sentence sentence


HTH :)

rachelk
08-02-2009, 07:11 AM
Thanks a lot for that :)