dongnao9525 2019-04-12 09:01
浏览 44
已采纳

查找数组或字符串中是否存在单词PHP [duplicate]

This question already has an answer here:

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

</div>
  • 写回答

1条回答 默认 最新

  • douzhan2027 2019-04-12 09:09
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?