Question

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

Was it helpful?

Solution

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) { ... }
}

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top