You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP实现多关键词字符串搜索:匹配任意关键词即返回结果

Simple PHP Multi-Keyword Search (No ElasticSearch Needed)

Got it, let's solve this multi-keyword search problem without overcomplicating things. The issue with just using stripos directly is that it only checks for the exact search string—so we need to adjust the logic to check both the full phrase and individual keywords. Here's a clean, reusable function that does exactly what you're asking for:

function multiKeywordSearch(string $target, string $search): bool {
    // First check if the entire search phrase exists (case-insensitive)
    if (stripos($target, $search) !== false) {
        return true;
    }
    
    // Split search into individual keywords (handle multiple spaces/empty terms)
    $keywords = array_filter(array_map('trim', explode(' ', $search)));
    
    // If no valid keywords after splitting, return false
    if (empty($keywords)) {
        return false;
    }
    
    // Check each keyword against the target string
    foreach ($keywords as $keyword) {
        if (stripos($target, $keyword) !== false) {
            return true;
        }
    }
    
    // None of the phrases/keywords matched
    return false;
}

How It Works:

  1. Full Phrase Check: First, we check if the entire search string exists in the target (using stripos for case-insensitive matching). This handles cases where someone searches for an exact phrase like "big tech".
  2. Keyword Splitting: If the full phrase isn't found, we split the search string into individual keywords. We use array_map('trim') to remove extra spaces around each term and array_filter to get rid of any empty entries (from multiple spaces).
  3. Individual Keyword Check: Loop through each keyword and check if it exists in the target. If any match is found, return true immediately.
  4. No Matches: If neither the full phrase nor any keywords are found, return false.

Test It With Your Example:

$string = "Apple is a big tech company!";
$search = 'Apple Logo';

var_dump(multiKeywordSearch($string, $search)); // Output: bool(true)

Customization Tips:

  • Case Sensitivity: If you want case-sensitive matching, replace stripos with strpos.
  • Different Delimiters: If you want to split keywords by commas (e.g., "Apple,Logo") instead of spaces, change explode(' ', $search) to explode(',', $search).
  • Minimum Keyword Length: Add a check inside the loop to skip very short keywords (like 1-2 characters) if needed: if (strlen($keyword) < 3) continue;.

This is lightweight, easy to integrate, and avoids the overhead of ElasticSearch for simple use cases.

内容的提问来源于stack exchange,提问作者I Am Stack

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 06:48:36