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

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器