Php: how to check if a string contains any of the listed keywords?

I have an array of strings.

I have an array of keywords.

i scroll through each row and store them in the mysql database if it contains any keywords.

I am currently using several stristr () which are becoming difficult.

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

+3
source share
5 answers

I would advise you to use regex for this

snipet:

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

see the preg_match_all documentation for reference

+5
source
foreach ( $strings as $string ) {
  foreach ( $keywords as $keyword ) {
    if ( strpos( $string, $keyword ) !== FALSE ) {
      // insert into database
    }
  }
}
+3
source
$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*/
+2

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

    }

  }

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

}

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

0

Source: https://habr.com/ru/post/1722074/


All Articles