How to > if values in array exist in the sentence ?

Discussion in 'PHP' started by meannn, Jan 5, 2010.

  1. #1
    Hello,

    I want to do something if my sentence include one of the words in this array, How to do that ?

    
    $sentence = "I dont give a shit";
    
    $values = array("lick","shit","pussy","horny");
    
    PHP:
    Thanks...
     
    meannn, Jan 5, 2010 IP
  2. n3r0x

    n3r0x Well-Known Member

    Messages:
    257
    Likes Received:
    4
    Best Answers:
    1
    Trophy Points:
    120
    #2
    
    $sentence = "I dont give a shit";
    
    $values = array("lick","shit","pussy","horny");
    $found = 0;
    foreach($values as $val) {
     if(strpos($sentence,$val) != -1) {
      //found one
      $found = 1;
     }
    }
    // if it found one or more $found = 1 else $found = 0
    
    
    PHP:
    this is just one way.. there are more ways to do this..
     
    n3r0x, Jan 5, 2010 IP
  3. JAY6390

    JAY6390 Peon

    Messages:
    918
    Likes Received:
    31
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Personally I'd use a boundary based regex of the words
    
    function to_regex($string) {
        return '%\b'.preg_quote($string).'\b%i';
    }
    $filter = array_map('to_regex', $values);
    foreach($filter as $val) {
        if(preg_match($val, $sentence) {
            //Do whatever here
        }
    }
    PHP:
    EDIT: Also, this is case insensitive

    Also, use google for this kind of thing, they're out there in the thousands
    http://www.google.com/search?hl=en&q=php+word+filter&aq=f&oq=&aqi=g1
     
    JAY6390, Jan 5, 2010 IP