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, arr开发者_JAVA百科ay("ship","fukc","blah"));
?
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
foreach ( $strings as $string ) {
foreach ( $keywords as $keyword ) {
if ( strpos( $string, $keyword ) !== FALSE ) {
// insert into database
}
}
}
$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*/
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 */
}
}
}
if(in_array($string, array("ship","fukc","blah")))
{
}
Documentation: http://php.net/manual/en/function.in-array.php
精彩评论