Finding data in an exploded term

Discussion in 'PHP' started by phatuis, Dec 12, 2009.

  1. #1
    Hello, say:

    $explode = explode(" ", $data)

    I want to see if a variable is found in the data when exploded, and if found, return 1 piece of code, if no found another piece of code.
     
    phatuis, Dec 12, 2009 IP
  2. mastermunj

    mastermunj Well-Known Member

    Messages:
    687
    Likes Received:
    13
    Best Answers:
    0
    Trophy Points:
    110
    #2
    which variable?
    what will be condition which when satisfied indicates that variable is found?

    put some more details with example to help you better..
     
    mastermunj, Dec 12, 2009 IP
  3. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #3
    $text = 'this is a test piece of text';
    $terms = explode(' ', $text);
    $found = false;
    $term = 'test';
    foreach($terms as $v) {
        if($term == $v) {
            $found = true;
            break;
        }
    }
    if($found) {
        //Term found code here
    } else {
        //Term not found code here
    }
    PHP:
     
    JAY6390, Dec 12, 2009 IP
  4. Wogan

    Wogan Peon

    Messages:
    81
    Likes Received:
    3
    Best Answers:
    2
    Trophy Points:
    0
    #4
    Wouldn't it be quicker to use:

    $search = "fox";
    $string = "The quick brown fox jumped over the lazy dog.";
    
    if (stripos($string, $search) === FALSE)
    {
      echo $search . " was not found";
    }
    else
    {
      echo $search . " was found";
    }
    PHP:
    That'll work if you're looking for a specific word in a string. If you're stuck with an array, you could try:

    $search = "fox";
    
    /* Just creating an array real quick */
    $string = "The quick brown fox jumped over the lazy dog.";
    $array = explode(" ", $string); 
    
    if (in_array($search, $array))
    {
      echo "Found $search.";
    }
    else
    {
      echo "Didn't find $search";
    }
    PHP:
     
    Wogan, Dec 12, 2009 IP