2

I want to look at a string and see if any of the words in the string match the words in a text file.

lets say i have a product.txt file and it contains:

apple sony dyson mcdonalds ipod

here is my code:

    <?php

$productFile = file_get_contents('products.txt', FILE_USE_INCLUDE_PATH);

/*
* product.txt file contains
* apple
* pc
* ipod
* mcdonalds
*/

$status = 'i love watching tv on my brand new apple mac';

    if (strpos($status,$productFile) !== false) {
        echo 'the status contains a product';
    }

    else{
        echo 'The status doesnt contain a product';
    }

?>

right now its telling me the status doesnt contain a product which it does, can anyone see where im going wrong?

Ricky
  • 77
  • 1
  • 4
  • 14

3 Answers3

4

You're searching for the word list as a whole in the string. Instead, you have to search for every word in the word list separately. For example, str_word_count can be used to split the string into words.

<?php

$productFile = file_get_contents('products.txt');
$products = str_word_count($productFile, 1);

$status = 'i love watching tv on my brand new apple mac';

$found = false;
foreach ($products as $product)
{
    if (strpos($status,$product) !== false) {
        $found = true;
        break;
    }
}

if ($found) {
    echo 'the status contains a product';
}
else {
    echo 'The status doesnt contain a product';
}

?>

You may also want to consider stripos instead of strpos for case-insensitive comparison.

Callidior
  • 2,899
  • 2
  • 18
  • 28
1
<?php

$productFile = file_get_contents('products.txt', FILE_USE_INCLUDE_PATH);

/*
* product.txt file contains
* apple
* pc
* ipod
* mcdonalds
*/

$status = 'i love watching tv on my brand new apple mac';
$status = str_replace(' ', '|', $status);

if ( preg_match('/'.$status.'/m',$productFile) ) {
    echo 'the status contains a product';
}
else {
    echo 'The status doesnt contain a product';
}
blue
  • 1,939
  • 1
  • 11
  • 8
0

First of all, I think you mixed up the variable order (Reference)

mixed strpos ( string $haystack , mixed $needle [, int $offset = 0 ] )

And then you have to check each word manually, the whole string does not exist in the file, just one word does. Create an array using explode() for instance and use a foreach loop.

Bowdzone
  • 3,827
  • 11
  • 39
  • 52