Forum Moderators: coopster
I was getting errors at the end of the while loop. It said something to the effect that one of the parameters for the strpos test was missing. I thought maybe I had some empty lines at the end of the file.
I was able to fix things by testing to see if the line is empty.
Does anyone have a guess why my original code was breaking? My last line break was on the same line as my last data point. So I did not have two line breaks next to each other at the end.
Is there a better way to rip through a file to test for a match?
$handle = fopen($_SERVER['DOCUMENT_ROOT']."/data.txt", "r");
while (!feof($handle)) {
$buffer = fgets($handle);
$pos = strpos(trim($buffer), trim($$name));
}$handle = fopen($_SERVER['DOCUMENT_ROOT']."/data.txt", "r");
while (!feof($handle)) {
$buffer = fgets($handle);
if (strlen($buffer)>0){
$pos = strpos(trim($buffer), trim($$name));
}
}
// ========================================================================
//=========================================================================
// NAME: find_string
// DATE CREATED: 05/31/2004
// DATE MODIFIED:
// PURPOSE:
//
// ========================================================================
// ========================================================================
function find_string($cString,$cRegex) {
$aFound = array();
preg_match( "/$cRegex/", $cString, $aFound );
return $aFound[1];
}
[example]
$file = 'file.txt'
$handle = @fopen($file, 'r');
$contents = @fread($handle, filesize($file));
$strPos = strpos('text to search', $contents);
if ($strPos!== false)
{
echo 'Found Text!';
}
fclose($handle);
[/example]
strpos() returns the postion of the first character in the string if it finds a match. If it finds no matches, then the if statement will evaluate to false or 0 (I think).