Jump to content

txt file search program needed


Flustered

Recommended Posts

I need a search engine for a web site that will search a .txt file and return each line as a result. I used a program called Search Engine Builder Pro v2.02, that came close, but it detects the .txt file as one big result, it doesn't read each line as a result. Any ideas? Thanks all!

 

P.S. If needed, I could put up a temp web site that would show what I have so far and what isn't working

 

P.S.S. I am an idiot on any scripting, so please make any answers in a manner that a 6 yr old would understand...lol (and sorry for any offense to 6 yr olds that may read this)

Link to comment
Share on other sites

Below are some lines from the type of txt. What I need is is you searched for "Followers", it would return 2 results (as I duplicated the line). What I have now, just shows the entire .txt as 1 result. If it finds the search word, I need it to return as a result, the entire line it is in as 1 result. For example:

Found 1 result:

Followers of the Unification Church are called ________*Moonies

Found 2 result:

Followers of the Unification Church are called ________*Moonies

 

I think it would need some way to block certain searchs, like single letters or numbers, so it doesn't go crazy

 

 

 

 

 

Followers of the Unification Church are called ________*Moonies

In which state is Mount St. Helens*Washington

Astronomy: Which planet does the moon Io belong to*Jupiter

Name Alley Oop's girl friend*Oola

What war lasted from june 5 to june 11, 1967*six day war

Basketball: The Seattle ________*Supersonics

What does a male cow have to undergo if it's being raised for beef*Castration

What is the art and science of mapmaking called*Cartography

Where is Queen Maud Land located*Antarctica

Kaos Most popular christmas shows in 2007*

11/27/2007 Freakin.Christmas 1903

11/18/2007 Stole.Christmas 1253

11/12/2007 Christmas.With.The.Sim 401 6765

11/22/2007 Christmas.Time 47400

11/22/2007 Times 4768     

Followers of the Unification Church are called ________*Moonies

In which state is Mount St. Helens*Washington

Astronomy: Which planet does the moon Io belong to*Jupiter

Name Alley Oop's girl friend*Oola

What war lasted from june 5 to june 11, 1967*six day war

Basketball: The Seattle ________*Supersonics

Subject, verb and object are parts of a _________*Sentence

This animal is found at the beginning of an encyclopedia*ardvark

In what country can the Big Merino, Big Murray Cod, Big Pineappe, and Big Worm be found in*Australia

Which kind is the DEEPEST sea*Coral Sea

A line drawn from an angle of a triangle to the mid-point of the opposite side is a(n) _______*Median

How long is the Le Mans Endurance motor race*Twenty four hours

Famous medical scale that reports the grade of consciousness of a patient*Glasgow

What is terebinth*turpentine tree

Frankish ruler Charles the Great is better known as _________*Charlemagne

Name Li'l Abner's favorite Indian drink*Kickapoo Joy Juice

Music: What year was Elvis Presley born*1935

Link to comment
Share on other sites

Something like this:

<?php

function search($keyword)
{
    $results = false;
    $lines   = file('search_data.txt');

    // escape characters which are sensitive to eregi()
    $symbols = array('[', ']', '-', '(', ')');
    $replace = array('\[', '\]', '\-', '\(', '\)');
    $keyword = str_replace($symbols, $replace, $keyword);

    foreach($lines as $line)
    {
        if(eregi($keyword, $line))
        {
            $line = str_replace($keyword, "<b>$keyword</b>", $line);
            $results[] = $line;
        }
    }

    return $results;
}

if(isset($_POST['submit']))
{
    if(!empty($_POST['keyword']) && strlen($_POST['keyword']) > 3)
    {
        $keyword        = $_POST['keyword'];
        $search_results = search($keyword);

        if(is_array($search_results))
        {
            echo 'The search term "<i><b>'. $keyword . '</b></i>" found ' . count($search_results) . ' search result(s):';

            echo '<ol><li>' . implode('</li><li>', $search_results) . '</li></ol>';
        }
        else
        {
            echo 'No results was returned';
        }
    }
    else
    {
        echo 'Invalid search term "<i><b>'. $_POST['keyword'] . '</b></i>"';
    }
}

?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Search word: <input type="text" name="keyword" /> <input type="submit" name="submit" value="Search" />
</form>

search_data.txt is the file which contains your search data.

Link to comment
Share on other sites

I'm getting an error, as this part of the code shows on the webpage and also I'm guessing its stopping any results from showing:


3) { $keyword = $_POST['keyword']; $search_results = search($keyword); if(is_array($search_results)) { echo 'The search term "'. $keyword . '" found ' . count($search_results) . ' search result(s):'; echo '

' . implode('
', $search_results) . '
'; } else { echo 'No results was returned'; } } else { echo 'Invalid search term "'. $_POST['keyword'] . '"'; } } ?> 


 

Thanks so much for helping!

Link to comment
Share on other sites

If you want the search box on the html page then you can copy the form code over to your html page, set the action attribute in the form tag to search.php, eg:

<form action="search.php" method="post">
    Search word: <input type="text" name="keyword" /> <input type="submit" name="submit" value="Search" />
</form>

When the form is submitted the browser will load search.php displaying the results.

Link to comment
Share on other sites

It's working pretty good now, but I had a question on a couple small issues. Can it be adjusted to search for more than one word?  And when you enter the search word and hit enter, it doesn't work, you have to use the mouse to click the button. Is this an easy issue to fix?

Link to comment
Share on other sites

It's working pretty good now, but I had a question on a couple small issues. Can it be adjusted to search for more than one word?

It certainly can, all you need to do is call the search() function fo each keyword entered in the search box.

 

And when you enter the search word and hit enter, it doesn't work, you have to use the mouse to click the button. Is this an easy issue to fix?

You'll need to use Javascript for that.

Link to comment
Share on other sites

Modified the code:

<?php

function keywordSearch($keyword)
{
    $results = false;
    $lines   = file('search_data.txt');

    $symbols = array('[', ']', '-', '(', ')');
    $replace = array('\[', '\]', '\-', '\(', '\)');
    $keyword = str_replace($symbols, $replace, $keyword);

    foreach($lines as $line)
    {
        if(eregi($keyword, $line))
        {
            $line = str_replace($keyword, "<b>$keyword</b>", $line);
            $results[] = $line;
        }
    }

    return $results;
}

function displaySearchResults()
{
    global $keyword_results, $keyword;

    $output = '';

    foreach($keyword_results as $keyword => $results)
    {
        $output .= '<p>The search term "<i><b>'. $keyword . '</b></i>" found ';

        if(is_array($results))
        {
            $output .= count($results) . ' search result(s):';

            $output .= '<ol><li>' . implode('</li><li>', $results) . '</li></ol>';
        }
        else
        {
            $output .= "no search results</p>\n\n";
        }
    }

    echo $output;
}

if(isset($_POST['submit']))
{
    if(!empty($_POST['keyword']) && strlen($_POST['keyword']) > 3)
    {
        $_POST['keyword'] = str_replace(array("\r\n", "\r", "\n"), "\n", $_POST['keyword']);
        $keyword_search = explode("\n", $_POST['keyword']);

        if(is_array($keyword_search))
        {
            foreach($keyword_search as $keyword)
            {
                if(strlen($keyword) > 3)
                    $keyword_results[$keyword] = keywordSearch($keyword);
            }
        }
        else
        {
             $keyword_results[$keyword_search] = keywordSearch($keyword_search);
        }

        displaySearchResults();
    }
    else
    {
        echo 'Invalid search term';
    }
}

?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Keywords:<br /><textarea name="keyword" cols="40" rows="4"><?php echo isset($_POST['keyword']) ? $_POST['keyword'] : null; ?></textarea>
    <p><input type="submit" name="submit" value="Search" /></p>
</form>

Link to comment
Share on other sites

can it be modified to search for words more at random? I noticed that if you had a line of <one two three>, it would search and find "one two" and "two three", but no results if search was for "one three". Also because of the format of data, there are dots and astericks, so if the data line was <one.two*three>, there would be no results for searching "one two". I really appreciate the time and effort in helping with this, as I get totally lost.

Link to comment
Share on other sites

Hi, sorry I haven't replied. I have modified the script a little to how I think you wanted:

<?php

function keywordSearch(&$keywords)
{
    global $keyword_count;

    $lines   = file('search_data.txt');
    $results = false;

    $symbols = array('[', ']', '-', '(', ')');
    $replace = array('\[', '\]', '\-', '\(', '\)');

    $colors  = array('#FF0000', '#0000FF', '#00FF00', '#FFFF00');

    $i = 0;
    foreach($lines as $line)
    {
        $keyword_found = false;

        foreach($keywords as $key => $keyword)
        {
            if(!isset($keyword_count[$keyword]))
            {
                $keyword_count[$keyword] = 0;
            }

            $keyword = str_replace($symbols, $replace, $keyword);

            if(eregi($keyword, $line))
            {
                $keyword_found = true;

                // remove answer from end of line
                $line = eregi_replace("\*([a-z0-9 ]+)", '?' , $line);
                $line = str_replace($keyword, "<span style=\"color: {$colors[$key]}; font-weight: bold;\">$keyword</span>", $line);

                $results[$i] = $line;

                $keyword_count[$keyword]++;
            }
        }

        if($keyword_found)
            $i++;
    }

    return $results;
}

function displaySearchResults()
{
    global $keyword_results, $keywords, $keyword_count;

    $output  = '<p>The keywords "<i><b>'. implode('</b></i>", "<i><b>', $keywords) . '</b></i>" found ' . count($keyword_results) . " result(s):\n";
    $output .= "<ol>\n  <li>" . implode("</li>\n  <li>", $keyword_results) . "</li>\n</ol>\n";

    echo "<p>$output</p>";
}

if(isset($_POST['submit']))
{
    if(!empty($_POST['keyword']))
    {
        $_POST['keyword'] = str_replace(array("\r\n", "\r", "\n"), "\n", $_POST['keyword']);
        $keywords = explode("\n", $_POST['keyword']);

        $keyword_results = keywordSearch($keywords);

        displaySearchResults();
    }
    else
    {
        echo 'Invalid search term';
    }
}

?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
    Keywords:<br /><textarea name="keyword" cols="40" rows="4"><?php echo isset($_POST['keyword']) ? $_POST['keyword'] : null; ?></textarea>
    <p><input type="submit" name="submit" value="Search" /></p>
</form>

Link to comment
Share on other sites

There is no need for you to apologize, your help has been so greatly appreciated. I feel bad that I am so ignorant that I have to ask for so much help. The change doesn't seem to work however. It shows  1 blank result for each multi-word try. i.e.

 

The keywords "one three" found 1 result(s):

 

1.

 

Single word search still works

 

 

Link to comment
Share on other sites

Bug fixed, forgot to add some in. Try:

<?php

function keywordSearch(&$keywords)
{
    global $keyword_count;

    $lines   = file('search_data.txt');
    $results = array();

    $symbols = array('[', ']', '-', '(', ')');
    $replace = array('\[', '\]', '\-', '\(', '\)');

    // colors for highlighting keywords
    $colors  = array( '#FF0000', // red
                      '#0000FF', // blue
                      '#99CC00', // green
                      '#CCCC00', // yellow
                      '#660066', // purple
                      '#FF0099'  // pink
                    );

    $i = 0;
    foreach($lines as $line)
    {
        $keyword_found = false;

        foreach($keywords as $key => $keyword)
        {
            if(!isset($keyword_count[$keyword]))
            {
                $keyword_count[$keyword] = 0;
            }

            $keyword = str_replace($symbols, $replace, $keyword);

            if(eregi($keyword, $line))
            {
                $keyword_found = true;

                // remove answer from end of line
                $line = eregi_replace("\*([a-z0-9 ]+)", '?' , $line);

                // highlight search keyword
                $line = eregi_replace("($keyword)", "<span style=\"color: {$colors[$key]}; font-weight: bold;\">\\1</span>", $line);

                $results[$i] = $line;

                $keyword_count[$keyword]++;
            }
        }

        if($keyword_found)
            $i++;
    }

    return $results;
}

function displaySearchResults()
{
    global $keyword_results, $keywords, $keyword_count;

    $output  = '<p>The keywords "<i><b>'. implode('</b></i>", "<i><b>', $keywords) . '</b></i>" found ' . count($keyword_results) . " result(s):\n";

    if(is_array($keyword_results) && count($keyword_results) > 0)
    {
        $output .= "<ol>\n  <li>" . implode("</li>\n  <li>", $keyword_results) . "</li>\n</ol>\n";
    }

    echo "<p>$output</p>";
}

if(isset($_POST['submit']))
{
    if(!empty($_POST['keyword']))
    {
        $_POST['keyword'] = str_replace(array("\r\n", "\r", "\n"), "\n", $_POST['keyword']);
        $keywords = explode("\n", $_POST['keyword']);

        $keyword_results = keywordSearch($keywords);

        displaySearchResults();
    }
    else
    {
        echo 'Invalid search term';
    }
}

?>

 

HTML

<form action="search.php" method="post">
    Keywords:<br /><textarea name="keyword" cols="40" rows="4"><?php echo isset($_POST['keyword']) ? $_POST['keyword'] : null; ?></textarea>
    <p><input type="submit" name="submit" value="Search" /></p>
</form>

Also note that I changed the search box to a textarea rather than a text field so you'll need to modify your search box HTML code to the HTML code posted above. When performing a search you now place each keyword on a separate line within the Keywords search box rather than a space.

Link to comment
Share on other sites

  • 2 weeks later...

sorry for delay, its real close, but there is one thing that would be better. On the multiple word search, it searches for either, and would be a lot better if it only searched for both (or multiple). For example, if you searched for "one" and "two" in search box, it shows all results with either word, instead of narrowing the search to only ones with both words.

 

Again, I want to thank you for the help and effort!!

Link to comment
Share on other sites

What I was trying to say was if you search for multiple words, it gives results of any one word in different colors, but can be a large result page. I was wondering if it could be changed so it only gave results that only contained all of the search words used.

 

So if you had the following lines in the data and searched for "one two"(on separate lines), only the "one two three" line would  be a result

 

one two three

one three four

one three five

 

Currently it would show all three lines as a result with "one" in red, and "two" in blue

 

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.