gweg
gweg

Reputation: 2882

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")); ?

Upvotes: 3

Views: 7097

Answers (5)

Jobst
Jobst

Reputation: 559

if(in_array($string, array("ship","fukc","blah")))
{

}

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

Upvotes: 0

rubayeet
rubayeet

Reputation: 9400

$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*/

Upvotes: 2

ksofa2
ksofa2

Reputation: 74

foreach ( $strings as $string ) {
  foreach ( $keywords as $keyword ) {
    if ( strpos( $string, $keyword ) !== FALSE ) {
      // insert into database
    }
  }
}

Upvotes: 3

RageZ
RageZ

Reputation: 27313

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

Upvotes: 5

Treby
Treby

Reputation: 1320

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 */

    }

  }

}

Upvotes: 0

Related Questions