View Single Post
  #8 (permalink)  
Old 08-19-06, 03:12 PM
Nico's Avatar
Nico Nico is offline
Community Leader
 
Join Date: Sep 2005
Location: Spain
Posts: 7,572
Thanks: 5
Thanked 27 Times in 24 Posts
Okay, give this a try.

PHP Code:
<?php

$search 
$_POST['search'];

if (
$search)
{
    
$file file('data.txt');
    
$keys preg_split('/[\s,]+/'preg_replace('/([^a-z0-9\s])/i'''trim($search) ) );
    
    if (
sizeof($keys) > 5)
    {
        die(
"Please enter less keywords");
    }
    else if (empty(
$keys[0]))
    {
        die(
"Please enter a valid keyword.");
    }
    
    
$pattern '/('implode('|'$keys) .')/i';
    
$matches = array();
    
    foreach (
array_values($file) AS $data)
    {
        list(
$month$day$year$info) = explode('|'trim($data) );
      
        if (
preg_match($pattern$info))
        {
            
$matches[mktime(000$month$day$year)][] = preg_replace($pattern'<span style="color:red;">$1</span>'$info);
        }
    }
    
    if (
sizeof($matches) > 0)
    {
        
ksort($matches);
        
$count 0;
        
        
printf('<p>%d match%s found.</p>'sizeof($matches), sizeof($matches) == NULL 'es');
        echo 
'<ol>';
    
        foreach (
$matches AS $time => $match)
        {
            list(
$month$day$year) = explode('-'date('M-d-Y'$time) );
            
$count++;
            
            echo 
'<center><b><font face="Times New Roman" size=2px">' $count'--' $month  '&nbsp;' $day ',&nbsp;' $year '</font></b></center>';
            echo 
'<font face="Times New Roman" size="2px">' current($match) .'</font>';
            echo 
"<p>";
            
            if (
$count >= 200)
            {
                break;
            }
        }
        
        echo 
'</ol>';
    }
    else
    {
        echo 
'<p>No matches found.</p>';
    }
}

?> 
<form action="" method="post">
    <input type="text" name="search" />
    <input type="submit" value="Search" />
</form>
Quote:
1) I am not real familar to patern matching etc. In the code you gave me, is it restrictive in any way? What I mean is that for some searches I get less results than I dowith using the stristr as I did earlier.
Hm, actually it should do the same, even better. It splits the string on every whitespace and searches for every word, case insensitive.

Quote:
2) In my first echo line, I want to display the month, year and date associated with that record. I tried this:
Cause these variables are the ones from the previous loop. They contain always the same values after the last loop.

The code above should do everything you want.
Reply With Quote