-2

I am trying to find if any of the string inside an array exist in array of words.

For example:

$key = ["sun","clouds"];
$results = ["Sun is hot","Too many clouds"];

If any of $key exists in $results to return true

With below script I get the result I want but only if word in $results is exact like the word in $key.

function contain($key = [], $results){
    $record_found = false;
    if(is_array($results)){

        // Loop through array
        foreach ($results as $result) {
             $found = preg_match_all("/\b(?:" .join($key, '|'). ")\b/i", $result, $matches);
             if ($found) {
                $record_found = true;
             }
        }

     } else {

         // Scan string to find word
         $found = preg_match_all("/\b(?:" .join($key, '|'). ")\b/i", $results, $matches);
         if ($found) {
            $record_found = true;
         }

      }

      return $record_found;

 }

If the word in $results is Enjoy all year round **sunshine** my function returns false as can not find word sun. How can I change my function to return true if string contain that string as part of word?

I want the word sun to match even with sun or sunshine.

TIA

Maria
  • 760
  • 2
  • 9
  • 22
  • There is no word boundary `\b` between `sun` and `shine` – The fourth bird Apr 12 '19 at 09:04
  • @Thefourthbird i know. The problem is i dont know if the word would be sunshine. That was an example. The $ressults may contain words like sunny,sunshine,sunday etc. is there any way i can change my script to return true or should i contain any possible word inside $key array? – Maria Apr 12 '19 at 09:07
  • 1
    The trick is: even if this is not an exact duplicate (as in: copy&paste that code), it helps you to solve your problem. Read it, change your code accordingly, and ask when that code still does not work – Nico Haase Apr 12 '19 at 09:10

1 Answers1

1

so as was said you can take the check from here and instead of regex use it + mb_strtolower in loop:

<?php
$keys = ["sun","clouds"];
$results = ["Sun is hot","Too many clouds"];

foreach ($keys as $key) {
    foreach ($results as $result) {     
        if (strpos(mb_strtolower($result), mb_strtolower($key)) !== false) {
            return true;
        }
    }
}
return false;
myxaxa
  • 1,391
  • 1
  • 8
  • 7