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

如何在PHP中提取字符串指定起止位置的内容

实现方案

使用PHP内置的substr()函数即可实现字符串指定片段的截取,注意该函数的索引从0开始计数:

  • 如果你需求里的166位、177位是从1开始计数的自然位置,对应截取参数为:起始偏移量165,截取长度12
  • 如果是从0开始计数的索引位置,对应参数为:起始偏移量166,截取长度11

修改后的完整代码如下:

<?php
$file = 'masterfile.out';
$searchfor = '125302532569';

// 防止浏览器解析为HTML
header('Content-Type: text/plain');

$contents = file_get_contents($file);
$pattern = preg_quote($searchfor, '/');
$pattern = "/^.*$pattern.*\$/m";

if(preg_match_all($pattern, $contents, $matches)){
    echo "Found matches:\n";
    $extracts = [];
    foreach ($matches[0] as $match_line) {
        // 先判断行长度是否足够,避免截取错误
        if (strlen($match_line) >= 177) {
            // 按从1开始计数的166-177位截取,参数不对可自行调整
            $extracts[] = substr($match_line, 165, 12);
        } else {
            $extracts[] = "当前匹配行长度不足,无法截取指定片段";
        }
    }
    echo implode("\n", $extracts);
} else {
    echo "No matches found";
}
?>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 14:54:03