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

PHP新手需求:对比CSV文件,匹配前缀过滤电话号码

Hey there! As a PHP newbie, let's walk through exactly how to solve this CSV matching and filtering task. I'll break down the logic step by step and provide a complete, commented code example that you can adapt to your files.

Step-by-Step Approach

First, let's outline what we need to do:

  1. Load the prefix data: Read x.csv and store all country prefixes along with their corresponding country names. We'll sort these prefixes by length (longest first) to avoid short prefixes accidentally matching longer ones first.
  2. Process the phone number file: Iterate through each row in y.csv, checking if the phone number starts with any of the prefixes from x.csv (and matches the corresponding country).
  3. Split the results: Write numbers that don't match any prefix to z.csv, and log the matching numbers (with their matched prefix) to a separate record file.

Complete PHP Code

Here's the full code with comments explaining each part:

<?php
// --------------------------
// Step 1: Load and prepare prefix data from x.csv
// --------------------------
$prefixData = [];
$prefixFile = fopen('x.csv', 'r');

// Skip the header row (first line of x.csv)
fgetcsv($prefixFile);

// Read each row and store prefix => country mapping
while (($row = fgetcsv($prefixFile)) !== false) {
    $prefix = trim($row[0]);
    $country = trim($row[1]);
    
    // Only add non-empty prefixes to our array
    if (!empty($prefix)) {
        $prefixData[$prefix] = $country;
    }
}
fclose($prefixFile);

// Sort prefixes by length (longest first) to prevent partial matches
usort(array_keys($prefixData), function($a, $b) {
    return strlen($b) - strlen($a);
});
$sortedPrefixes = array_flip(array_keys($prefixData));
foreach ($sortedPrefixes as $prefix => &$val) {
    $val = $prefixData[$prefix];
}
unset($val);

// --------------------------
// Step 2: Process y.csv and generate output files
// --------------------------
// Initialize output files
$zFile = fopen('z.csv', 'w');
$matchedFile = fopen('matched_records.csv', 'w');

// Write headers to both output files
fputcsv($zFile, ['国家', '电话号码']);
fputcsv($matchedFile, ['国家', '电话号码', '匹配前缀']);

// Read phone number data from y.csv
$phoneFile = fopen('y.csv', 'r');
// Skip the header row of y.csv
fgetcsv($phoneFile);

while (($row = fgetcsv($phoneFile)) !== false) {
    $phoneCountry = trim($row[0]);
    $phoneNumber = trim($row[1]);
    $matchedPrefix = null;

    // Check if the number matches any prefix (for the same country)
    foreach ($sortedPrefixes as $prefix => $prefixCountry) {
        // Match both country and prefix to avoid cross-country false matches
        if ($phoneCountry === $prefixCountry && str_starts_with($phoneNumber, $prefix)) {
            $matchedPrefix = $prefix;
            break; // Stop checking once we find the longest matching prefix
        }
    }

    // Route the row to the correct file
    if ($matchedPrefix) {
        fputcsv($matchedFile, [$phoneCountry, $phoneNumber, $matchedPrefix]);
    } else {
        fputcsv($zFile, [$phoneCountry, $phoneNumber]);
    }
}

// Clean up: close all open files
fclose($phoneFile);
fclose($zFile);
fclose($matchedFile);

echo "Processing complete! Check z.csv for filtered numbers and matched_records.csv for the matched entries.";
?>

Key Notes for Newbies

  • CSV Handling: Using fgetcsv and fputcsv is way better than manually splitting strings—these functions handle commas inside quoted fields automatically.
  • Prefix Sorting: Sorting prefixes by length ensures that longer, more specific prefixes are checked first. For example, if you have both 44 and 4474, we don't want 44 to match a number starting with 4474 before we check the longer prefix.
  • PHP Version Compatibility: str_starts_with works in PHP 8.0+. If you're using an older version, replace it with:
    substr($phoneNumber, 0, strlen($prefix)) === $prefix
    
  • File Paths: Make sure your CSV files are in the same folder as your PHP script, or use full file paths (like '/var/www/x.csv') if they're elsewhere.

Example Output

After running the script:

  • z.csv will contain all numbers that didn't match any prefix (exactly like your desired example)
  • matched_records.csv will log every number that did match a prefix, along with the prefix and country

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:38:21