simplyblue
simplyblue

Reputation: 2339

php problem searching words in a text file

I use the following code to search the text file:

$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$Pos = strpos($data,$query);
if ($Pos)
{
    echo "Found";
}
else
{
    echo "Not Found";
}

Let the text file be:

orange_red blue_gray yellow_blue white_black

It finds red at orange_red,but i want to match the whole word. For example: If the text to be searched is to be red

I want it to return false because red does not exist independently it is part of word orange_red.

In brief i want to search words delimited by space

Searching red and orange should return false and searching orange_red should return true.

Upvotes: 2

Views: 773

Answers (5)

TeamBlast
TeamBlast

Reputation: 428

$query="red";
$FileName = "search.txt";
foreach (explode(" ", strtolower(file_get_contents($FileName)) as $word) {
    if (strtolower($query) == $word) {
        $found = true;
        break;
    }
}
echo $found ? "Found" : "Not found";

Meh, a little less efficient, but it gets the job done.

Upvotes: 1

user456814
user456814

Reputation:

Try using strpos with " $query ", or use a regular expression and preg_match:

$query = "red";

if (strpos($data, " {$query} ") !== false) {
    // data contains " red "
}
// OR
if (preg_match("/(^{$query}( )|( ){$query}( )|( ){$query}$)/", $data) === 1) {
    // match found
}

Upvotes: -1

ETWW-Dave
ETWW-Dave

Reputation: 732

This is the easiest/fastest way I can think of:

$query    = "red"; 
$FileName = "search.txt";

if(preg_match("/\b" . $query . "\b/i"), file_get_contents($FileName))
{
    echo "Found";
}
else
{
    echo "Not Found";
}

\b matches a word boundary, so it will only return stand-alone results for $query. preg_match returns an int denoting the number of times the pattern was found (which will be either 0 or 1, as preg_match stops after the first match - use preg_match_all to get an accurate count of how many times the pattern appears in the target).

Upvotes: 1

Jess
Jess

Reputation: 8700

Try this, splits the data at a space, and then sees if the query is in the array.

$query="red";
$FileName = "search.txt";
$fh = fopen($FileName, 'r') or die("Can't open file");
$data = fread($fh, filesize($FileName));
$items = explode(" ", $data);
$Pos = array_search ($query, $items);
if($Pos !== FALSE)
{
    echo "Found";
}
else
{
    echo "Not Found";
}

Upvotes: 0

GolezTrol
GolezTrol

Reputation: 116100

Split the string into an array using explode. Then search the array using array_search to see if it contains your exact word.

Upvotes: 1

Related Questions