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

Laravel(PHP)中忽略星号比对数组字符串并匹配相同编码

解决方案

核心逻辑

遍历两组数组的所有组合,对每一对模板字符串(带*)和编码字符串,做以下校验:

  • 编码长度必须为12
  • 模板中所有非*的字符,必须与编码对应位置的字符完全一致

代码实现(Laravel/PHP)

<?php

$templateArray = ['*01***12*4**','0*****54*41*','***18*******','*2*7**3***1','***42*12*4**'];
$codeArray = ['128420120400','012189654700','321501481012','88114474111'];

$matchedCodes = [];

foreach ($templateArray as $template) {
    foreach ($codeArray as $code) {
        // 跳过长度不符合要求的编码
        if (strlen($code) !== 12) {
            continue;
        }

        $matchFlag = true;
        // 逐个字符比对
        for ($i = 0; $i < 12; $i++) {
            $tChar = $template[$i] ?? '';
            $cChar = $code[$i] ?? '';

            if ($tChar !== '*' && $tChar !== $cChar) {
                $matchFlag = false;
                break;
            }
        }

        if ($matchFlag) {
            // 去重存储,避免同一编码匹配多个模板时重复存入
            if (!in_array($code, $matchedCodes)) {
                $matchedCodes[] = $code;
            }
        }
    }
}

// 输出结果
dd($matchedCodes);

代码说明

  1. 双层循环遍历所有模板与编码的组合
  2. 先过滤长度非12的编码,减少无效比对
  3. 逐字符校验模板非星号位置与编码的一致性,一旦不匹配立即终止当前比对
  4. 结果数组自动去重,确保每个编码只存一次

性能优化建议(大数据量场景)

如果数组元素较多,可将模板转换为正则表达式,用正则匹配替代逐字符遍历,提升效率:

foreach ($templateArray as $template) {
    // 把模板中的*替换为正则通配符.,同时转义特殊字符
    $pattern = '/^' . str_replace('*', '.', preg_quote($template, '/')) . '$/';
    
    foreach ($codeArray as $code) {
        if (strlen($code) === 12 && preg_match($pattern, $code)) {
            if (!in_array($code, $matchedCodes)) {
                $matchedCodes[] = $code;
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 15:57:37