如何在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
相关产品推荐
相关产品推荐

