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

PHP解析文本文件:提取首项及每间隔15项的引号内内容

用PHP提取指定引号内内容的解决方案

嘿,这个需求用PHP处理起来其实挺清晰的,我给你两种靠谱的实现思路,优先推荐第一种,因为更稳妥:

方法一:利用CSV解析函数(强烈推荐)

你的文本本质是CSV格式(逗号分隔、双引号包裹字段),PHP内置的CSV处理函数能自动处理各种边界情况(比如字段内的逗号、转义引号),比正则表达式可靠得多。

具体步骤:

  1. 把文本拆分成单条记录(你的示例里两条记录用" "分隔,先处理这个);
  2. 用str_getcsv()把每条记录解析成数组,每个元素就是一个引号内的内容;
  3. 提取数组的第一个元素(对应第一个引号),再提取每第15个元素(注意数组索引从0开始,第15个内容对应的索引是14)。

代码示例:

// 你的原始文本
$text = '"Prairie Ridge","Prairie Ridge","WA","Washington","53053","Pierce","47.1443","-122.1408","","","1349.8","polygon","False","America/Los_Angeles","98360 98391","1840037882" "Edison","Edison","WA","Washington","53057","Skagit","48.5602","-122.4311","","","127.4","polygon","False","America/Los_Angeles","98232","1840037883"';

// 拆分两条记录(处理" "分隔符)
$records = explode('" "', $text);
// 清理每条记录首尾的引号
$records = array_map(function($item) {
    return trim($item, '"');
}, $records);

// 存储结果的变量
$firstItems = [];
$fifteenthItems = [];

foreach ($records as $record) {
    // 将单条记录解析为CSV数组
    $fields = str_getcsv($record, ',', '"');
    
    // 提取第一个引号内容
    $firstItem = $fields[0] ?? null;
    $firstItems[] = $firstItem;
    
    // 提取第15个引号内容(索引14,因为数组从0开始计数)
    $fifteenthItem = $fields[14] ?? null;
    $fifteenthItems[] = $fifteenthItem;
}

// 输出结果
echo "所有第一个引号内容:" . implode(', ', $firstItems) . "\n";
echo "所有第15个引号内容:" . implode(', ', $fifteenthItems) . "\n";

方法二:使用正则表达式(适合格式极规整的场景)

如果你的文本绝对不会出现转义引号、字段内逗号这类情况,也可以用正则匹配所有引号内的内容,再筛选目标元素。

代码示例:

$text = '"Prairie Ridge","Prairie Ridge","WA","Washington","53053","Pierce","47.1443","-122.1408","","","1349.8","polygon","False","America/Los_Angeles","98360 98391","1840037882" "Edison","Edison","WA","Washington","53057","Skagit","48.5602","-122.4311","","","127.4","polygon","False","America/Los_Angeles","98232","1840037883"';

// 匹配所有双引号内的内容(假设没有转义引号)
preg_match_all('/"([^"]*)"/', $text, $matches);
$allQuotedContents = $matches[1];

// 获取第一个引号内容
$firstContent = $allQuotedContents[0] ?? null;

// 获取之后每第15个引号内容(从索引14开始,每隔15个取一次)
$everyFifteenthContents = [];
for ($i = 14; $i < count($allQuotedContents); $i += 15) {
    $everyFifteenthContents[] = $allQuotedContents[$i];
}

// 输出结果
echo "第一个引号内容:$firstContent\n";
echo "每第15个引号内容:" . implode(', ', $everyFifteenthContents) . "\n";

注意:这种方法的局限性很明显——如果遇到字段内有转义引号(比如"She said ""hi""!"),正则会匹配错误,所以只适合格式完全可控的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:38:55