Tejas Navghane Tejas Navghane - 1 month ago 7
PHP Question

How to search if keywords from a string are present in an array?

I have a string of 200 characters max also, an array of 4000 elements. Each element in the array is different and may contain upto 3 words.

I want to get all those keywords that I have in my string which are present in the array.

For e.g.:

$str = "This is my test string. Please copy this strings.";

$arr = ['is', 'my test', 'test string', 'strings'];

So, I should get result as is, my test, test string, strings keywords found from array.

Answer

You could do something like this:

<?php

$str = "This is my test string. Please copy this strings.";
$arr = ['is', 'my test', 'test string', 'strings'];
$results = [];

foreach($arr as $stringToEvaluate){

  // If the $stringToEvaluate is found in $str
  // then you push it to the $results array

  if(strpos($str, $stringToEvaluate) !== false){
    $results[] = $stringToEvaluate;
  }

}

print_r($results);
Comments