user1062058
user1062058

Reputation: 275

Searching for a keyword in a text file

I'm working on a PHP search script that scans a text file repository of packages on a website and returns the URL of each match. The text files looks as followed:

PACKAGE NAME: package_one
PACKAGE LOCATION: ./package_one
PACKAGE VERSION: 0.1.2

PACKAGE NAME: package_two
PACKAGE LOCATION: ./package_two
PACKAGE VERSION: 0.2.1

PACKAGE NAME: package_three
PACKAGE LOCATION: ./package_three
PACKAGE VERSION: 1.3.4

PACKAGE NAME: package_one
PACKAGE LOCATION: ./package_one
PACKAGE VERSION: 0.1.2

My search script currently looks as followed:

<?
$search = $_POST['search']; //Passed from a user input form

$data_file = file('http://www.example.com/data_file.txt'); //The text file repository

    $final_concatenated_results = "";

    for ($i = 0, $found = FALSE; isset($data_file[$i]); $i++) {
        if (trim($data_file[$i]) === $search) { 
        $cleanse = trim($data_file[++$i]);
        $output_part_one = strstr($cleanse, '.');
        $output_part_two = "http://www.example.com/packages_repository/".$output_part_one;
        $add_this = "<a href='$output_part_two'>$output_part_two</a>"."<br/>";
        $found = TRUE;
        $final_concatenated_results.=$add_this;
    } }

    if ($found == TRUE) {
        echo $final_results;
    }

    if ($found == FALSE) {
        echo "Error, package not found.";
    }
?>

For example, if "PACKAGE NAME: package_two" were typed in verbatim this would be the output -- http://www.example.com/packages_repository/./package_one which works fine.

Ideally, I'd like to know how to change my code so instead of typing in "PACKAGE NAME: package_two", one could simply type in "package_two" or even some like "two" or "tw". How much tweaking would that need?

Also, I made a variable to concatenate all of the resulting URLs to one string, so if "package_one" were searched, it would return two URLS... I don't think I did the code right as it only produces the one URL.

** I should mention that immediately after the package name is matched, it finds the next string following "PACKAGE LOCATION: ." to grab the URL

Any input is appreciated, thank you!

Upvotes: 1

Views: 1274

Answers (2)

jeroen
jeroen

Reputation: 91734

Here you are looking for an exact match:

if (trim($data_file[$i]) === $search) { 

You can use stripos to see if your search string appears in the line:

if (stripos($data_file[$i], $search) !== FALSE) {

Note that you need the !== comparison because stripos can evaluate to 0.

Upvotes: 2

Gregor
Gregor

Reputation: 4434

Have a look at the strpos() function:

if(strpos(trim($data_file[$i],$search) != false)

It checks if your search string (the needle) is inside the haystack (your current input line). http://php.net/manual/en/function.strpos.php

Upvotes: 1

Related Questions