1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.
  2. Better Analytics for WordPress Get It Free

Multiple keyword loop?

Discussion in 'PHP' started by MrLeN, Jun 14, 2014.

  1. #1
    If I have this text file:

    ---keywords.txt
    banana
    grapes
    apple
    mango
    orange
    pear
    coconut
    strawberry
    ---

    ..and I want to see if any of those words are in a string:

    ie:

    If (banana or apple or orange or pear are contained in my text file) {
    $keyword = "the word that was found";
    }

    for example: if apple was a line in the text file, then:

    $keyword = "apple"; //apple was found in the list and has become the $keyword

    also, if there are multiple keywords - just the first one found would do.

    ie: If both apple and pear were in the list then Keyword would become apple.

    I can find examples of how to check if a word is in a list online, but I can't find an example of how to check if a word is in a list and then make that word the value of a variable.
     
    Solved! View solution.
    MrLeN, Jun 14, 2014 IP
  2. #2
    From the docs of: http://www.php.net//manual/en/function.fgets.php + the isset check:

    
    <?php
    // Items or item to look for
    $lookingFor = array(
        'orange' => true,
        'apple' => true,
    );
    $keywordFound = false;
    // Open file
    $handle = fopen("keywords.txt", "r");
    if ($handle) {
         // Get line
         while (($buffer = fgets($handle, 4096)) !== false) {
            // If line is found in array, output and stop looking
            if (isset($lookingFor[$buffer])) {
                 $keywordFound  = $buffer;
                 break;
            }
        }
        if (!feof($handle)) {
            echo "Error: unexpected fgets() fail\n";
        }
        fclose($handle);
    }
    
    if ($keywordFound  !== false) {
        echo   echo "$keywordFound found in file";
    }
    
    PHP:
     
    ThePHPMaster, Jun 14, 2014 IP
    MrLeN likes this.
  3. MrLeN

    MrLeN Active Member

    Messages:
    394
    Likes Received:
    7
    Best Answers:
    0
    Trophy Points:
    60
    #3
    Thank you - that is just what I need!

    I appreciate your response :)
     
    MrLeN, Jun 14, 2014 IP