2

if get an input from the user and i wanted to search the file for any results, and display the results:

$searchValue = $_POST['search'];

$handle = @fopen("home.txt","r");
# read line by line
while (($buffer = fgets($handle, 4096)) !== false && // the condtion for the $searchValue) {
    echo '<tr>';
        $array = explode(',', $buffer);
    foreach($array as $val){
         echo '<td>'.$val.'</td>';      
        } 
    echo '</tr>';       
}

i dnt get what i have to do, i just want to display the rows in the text file with relevent $searchvalues

getaway
  • 8,792
  • 22
  • 64
  • 94

2 Answers2

1

I would even recommend using the file command:

array file  ( string $filename  [, int $flags = 0  [, resource $context  ]] )

Reads a file in with each line as an element in the array. From there, you would iterate each line (you mentioned returning the rows in the file that matched which is why I recommend file(...) ):

if (($fileLines = file('home.txt')) !== false)
{
  foreach ($fileLines as $line)
  {
    if (strpos($line, $searchVal) !== false)
    { // match found
      echo '<tr><td>'.str_replace(',','</td><td>',trim($line)).'</td></tr>';
    }
  }
}

No use exploding the array just to rejoin it again. You could also explode it then implode() it with the </td><td> as well.

Also, it seems like your file has rows of CSVs. If that's the case, you may want to iterate each row, then explode(...) the items and perform an in_array(...) (or iterate through with strpos for partial matches again) on the exploded variable. e.g.:

$values = explode(',',$line);
// array search (while entries)
if (in_array($searchVal,$values)) { ... }
// array search with partial matches
foreach ($values as $val) {
  if (strpos($val,$searchVal) !== false) { ... }
}
Brad Christie
  • 100,477
  • 16
  • 156
  • 200
  • thanks, for the post +1, what did you mean by the file command – getaway Nov 04 '10 at 14:15
  • File is the same as fopen,fgets,fclose but does all the work for you. It takes a file and loads up an array with each line in the file.Consequently I find it much cleaner to take a file and push it in to a $var in one line (though I've never formally tested performance, I would /assume/ [never good to] it would be faster for PHP to open, parse and clsoe the file then to do so myself) – Brad Christie Nov 04 '10 at 18:18
0

What you're looking for is strpos()

int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

Returns the numeric position of the first occurrence of needle in the haystack string.

Returns the position as an integer. If needle is not found, strpos() will return boolean FALSE.

Soufiane Hassou
  • 17,257
  • 2
  • 39
  • 75