首页 > 解决方案 > 字符串上的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

    )
)                      

标签: phpsubstr

解决方案


您可以创建一个像这样的函数来使用块大小进行拆分。注意:由于$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.....................................
)

推荐阅读