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

PHP如何筛选包含另一平数组任意元素为子串的数组元素?

实现方案说明

不一定需要手动写嵌套循环,PHP内置的函数可以实现更简洁的写法,不同场景可以选不同方案:


方案1:正则匹配方案(无手动嵌套循环,代码简洁)

把$array1的关键词拼接为正则匹配规则,一次遍历$array2即可完成筛选,底层遍历逻辑由PHP内核实现,性能比手动写PHP层嵌套循环更好,尤其是关键词量较大的场景。

<?php
$array1 = ["apple", "banana", "grape", "watermelon", "taro", "coffee", "green tea", "tomato", "cabbage"];
$array2 = ["there is apple", "there is banana", "there is lemon", "there is melon", "there is cucumber"];

// 先对关键词做正则转义,避免特殊字符导致正则报错,再拼接为 关键词1|关键词2 的匹配规则
$pattern = '/' . implode('|', array_map('preg_quote', $array1)) . '/';

// 筛选出符合规则的元素
$result = array_filter($array2, fn($item) => preg_match($pattern, $item));

// 可选:重置数组的连续索引
$result = array_values($result);

print_r($result);
// 输出:Array ( [0] => there is apple [1] => there is banana )
?>

方案2:手动嵌套循环(可控性高,适合小数据量场景)

如果关键词量很小,手动嵌套循环的逻辑更直观,不需要处理正则转义,不容易出现边界问题,记得匹配到就跳出内层循环减少无效遍历:

<?php
$array1 = ["apple", "banana", "grape", "watermelon", "taro", "coffee", "green tea", "tomato", "cabbage"];
$array2 = ["there is apple", "there is banana", "there is lemon", "there is melon", "there is cucumber"];

$result = [];
foreach ($array2 as $item2) {
    foreach ($array1 as $item1) {
        // PHP8及以上用str_contains,低版本替换为 strpos($item2, $item1) !== false
        if (str_contains($item2, $item1)) {
            $result[] = $item2;
            break; // 匹配到任意关键词就跳出内层循环
        }
    }
}

print_r($result);
// 输出:Array ( [0] => there is apple [1] => there is banana )
?>

选型建议

  • 关键词量小于100的场景,两种方案性能差异可以忽略,选你更容易维护的即可
  • 关键词量较大的场景优先选正则方案,性能优势更明显
  • 如果关键词包含大量正则特殊字符(如.、*、/等),优先选手动循环方案,不需要处理转义逻辑

内容的提问来源于stack exchange,提问作者wwwrrrxxx

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 16:39:02