0

I have two arrays

$setWords = array ('one','two','three');
$setSentences = array('There is one cloud in the sky', 'A dog has four legs' , 'There are three cars parked outside');

I tried the following but it didn't work.

if(array_intersect($setWords , $setSentences) == true) {
print_r($setSentences);
}

In this case it would be There is one cloud in the sky and There are three cars parked outside.

2 Answers 2

3

I love preg_grep:

$result = preg_grep('/'.implode('|', $setWords).'/', $setSentences);
print_r($result);
Sign up to request clarification or add additional context in comments.

Comments

2

This won't work. The array_intersect function only checks values that are exactly the same. You need to manually run over the arrays and compare contents using the strpos function.

Something like this:

foreach( $setWords as $word ) {
  foreach( $setSentences as $sentence ) {
    if( strpos( $sentence, $word ) !== false ) {
      echo "found " . $word . " in " . $sentence . "<br />";
    }
  }
}

1 Comment

Excellent. I can't believe it was so simple :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.