php - 字符串上的PHP多个substr
问题描述
我有一个字符串,我为其提供了一个字符串索引。
我正在创建一个读取它的过程,我想知道是否存在我忽略或不知道的 php 函数来更轻松地执行此过程。
$数据:
Invoice No..... Sale Type Desc...... Misc Amt.... Misc Acc.. Misc Acc Desc.....................................
FOCF219611 CUSTOMER -0.02 8050 TOOLS & SUPPLIES - SERVICE
FOCF219669 CUSTOMER -14.49 8050 TOOLS & SUPPLIES - SERVICE
$字段索引:
Array (
[0] => 15
[1] => 20
[2] => 12
[3] => 10
[4] => 50
)
拆分$data
成$headers
数组:
array_push($headers, substr($data, 0, $fieldIndexes[0]));
array_push($headers, substr($data, $fieldIndexes[0], $fieldIndexes[1]));
array_push($headers, substr($data, $fieldIndexes[1], $fieldIndexes[2]));
array_push($headers, substr($data, $fieldIndexes[2], $fieldIndexes[3]));
array_push($headers, substr($data, $fieldIndexes[3], $fieldIndexes[4]));
是否有可以删除部分字符串的函数 - 就像array_shift
字符串一样?我在想我可以循环$fieldIndexes
,从字符串的开头提取第一个长度,依此类推,直到字符串为空并将其压缩为 3 行并使其可移植到任意数量的 fieldIndexes?
期望的结果:
Array
(
[HEADERS] => Array
(
[0] => Invoice No
[1] => Sale Type Desc
[2] => Misc Amt
[3] => Misc Acc
[4] => Misc Acc Desc
)
[1] => Array
(
[Invoice No] => FOCF219611
[Sale Type Desc] => CUSTOMER
[Misc Amt] => -0.02
[Misc Acc] => 8050
[Misc Acc Desc] => TOOLS & SUPPLIES - SERVICE
)
)
解决方案
您可以创建一个像这样的函数来使用块大小进行拆分。注意:由于$fieldIndexes
数组中的每个大小不包括列之间的空间,所以我在每个长度上加了一个(15+1、20+1、...)
<?php
$headerString ="Invoice No..... Sale Type Desc...... Misc Amt.... Misc Acc.. Misc Acc Desc.....................................";
$fieldIndexes = [ 15+1, 20+1, 12+1, 10+1, 50+1];
function getParts($string, $positions){
$parts = array();
foreach ($positions as $position){
$parts[] = substr($string, 0, $position);
$string = substr($string, $position);
}
return $parts;
}
print_r(getParts($headerString, $fieldIndexes));
?>
结果:
Array
(
[0] => Invoice No.....
[1] => Sale Type Desc......
[2] => Misc Amt....
[3] => Misc Acc..
[4] => Misc Acc Desc.....................................
)
推荐阅读
- android - 即使从缓存中加载图像,滑行也需要时间来加载图像?
- svg - 重新计算路径上的 SVG 变换并保留组
- azure - 从 Key Vault 机密部署 Web 应用证书并将其用于创建 SSL 绑定 - LinkedAuthorizationFailed
- firebase - firebase 如何仅部署 express() 应用程序的特定功能
- r - 每个 ID 的总和取决于另一个变量
- c - 如何将 CSV 文件中的数据存储到结构中,然后返回该结构
- java - 错误:不是实体。但@Entity 和 persistence.xml 正确
- python-3.x - 将docx文件转换为html python3
- python - numpy.matrix 和 np.asmatrix 有什么区别吗?
- c - 释放数据结构的错误方法