Monday, February 21, 2011

php:how to check if string contains any of the listed keyword ?

i have an array of strings.

I have an array of keywords.

i loop through each string, and need to store them to mysql database if it contains any of the keywords.

currently i am using multiple stristr(), which is getting difficult.

is it possible to do something like stristr($string, array("ship","fukc","blah")); ?

From stackoverflow
  • try using in_array()

    for ($i = 0 ; $i < count($arrayString); $i++){
    
      for ($j = 0 ; $j < count($arrayKeyWord); $j++){
    
        if (in_array($arrayString[$i],$arrayKeyWord[$j]) == true){
          /* mysql code */
    
        }
    
      }
    
    }
    
  • I would advice you to use regular expresion for that

    snipet:

    preg_match_all('|(keyword1|keyword2|keyword3)|', $text, $matches);
    var_dump($matches);
    

    see the documentation of preg_match_all for reference

  • $to_be_saved = array();
    foreach($strings as $string) {
      foreach($keywords as $keyword) {
         if(stripos($string, $keyword) !== FALSE){
            array_push($to_be_saved, $keyword);
         }
      }
    

    }

    /*save $to_be_saved to DB*/
    
  • foreach ( $strings as $string ) {
      foreach ( $keywords as $keyword ) {
        if ( strpos( $string, $keyword ) !== FALSE ) {
          // insert into database
        }
      }
    }
    
  • if(in_array($string, array("ship","fukc","blah"))) {

    }

    see http://au.php.net/manual/en/function.in-array.php

0 comments:

Post a Comment