Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

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

like image 288
gweg Avatar asked Dec 01 '25 09:12

gweg


2 Answers

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

like image 112
RageZ Avatar answered Dec 05 '25 15:12

RageZ


foreach ( $strings as $string ) {
  foreach ( $keywords as $keyword ) {
    if ( strpos( $string, $keyword ) !== FALSE ) {
      // insert into database
    }
  }
}
like image 36
ksofa2 Avatar answered Dec 05 '25 15:12

ksofa2



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!