在串PHP多SUBSTR

问题描述 投票:1回答:2

我有一个针对我提供的字符串索引的字符串。

我创建一个进程读它,我想知道如果有一个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

$ fieldIndexes:

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

    )
)                      
php substr
2个回答
2
投票

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

0
投票

这样的(因为我说在评论)

$str = 'Invoice No..... Sale Type Desc...... Misc Amt.... Misc Acc.. Misc Acc Desc.....................................';

$f = fopen('php://temp', 'w+');
fwrite($f, $str);
rewind($f);
$headers = [];

$header = '';
while(false !== ($c = fgetc($f))){
    if($c != '.'){
        $header .= $c;
    }elseif(!empty($header)){
        $headers[] = trim($header);
        $header = '';
    }
}

print_r($headers);

输出

Array
(
    [0] => Invoice No
    [1] => Sale Type Desc
    [2] => Misc Amt
    [3] => Misc Acc
    [4] => Misc Acc Desc
)

注意:我这样做是不使用偏移,但我在评论中提到它,我喜欢做这样奇怪的事情。这是令人愉快的。

当然,你可能只是这样做了相同的结果:

$str = 'Invoice No..... Sale Type Desc...... Misc Amt.... Misc Acc.. Misc Acc Desc.....................................';

print_r(array_filter(array_map('trim',explode('.', $str))));

但是,这远远要容易。

Sandbox

如果你不喜欢键在所有古怪的你可以在吸盘一圈的array_values。

 print_r(array_values(array_filter(array_map('trim',explode('.', $str)))));

LOL,另一个星期一。

UPDATE

您可以使用文件流wappers定为CSV文件读了。在PHP5.4(我觉得还是5.3)的SplFileObj缺少fgetcsv和我用他们一招修补该类.... :)

这是我的一点(但也有很多我不知道)

$str = 'Invoice No..... Sale Type Desc...... Misc Amt.... Misc Acc.. Misc Acc Desc.....................................
somedata .... someother stuff ... foobar ... hello ... world..
';

//pretend this is a real file
$f = fopen('php://temp', 'w+');
fwrite($f, $str);
rewind($f);
$headers = [];
$num_headers = 0;

$i = 1;
while(false !== ($c = fgetcsv($f))){

     //if there is only one element assume the delimiter is wrong
    if(count($c) == 1){
        //you could test the string for multiple delimiters and change
        /*
         if(strpos($c, '.')){
            $regex = '/\.+/'
         }else if(strpos($c, '~')){
            $regex = '/~+/'
         } etc....
        */

        //use memory buffer to fix files with .'s but still read them as
        //a normal CSV file, php://memory is really fast.
        //and this gives us all the parsing benefits of fgetcsv
        //you could use any delimiter here you want.
        $fixed =  trim(preg_replace('/\.+/', ',', $c[0]),',');
        $m = fopen('php://memory', 'w+');
        fwrite($m, $fixed);
        rewind($m);
        $c = fgetcsv($m);
    }
    //trim any spaces, not a bad idea anyway
    $c = array_map('trim', $c);

    //if no headers use the first line of file as the header
    if(empty($headers)){
        $headers = $c;
        //count them (see below)
        $num_headers = count($headers);
        continue;
    }

     //array_combine is a good choice for header => values
     //but the arrays have to be the same size
    if(count($c) != $num_headers) die("missing dilimter on line {$i}");

    $line = array_combine($headers, $c);

    //continue with normal csv opperation
    print_r($line);

    ++$i; //track the line number
}

产量

Array
(
    [Invoice No] => somedata
    [Sale Type Desc] => someother stuff
    [Misc Amt] => foobar
    [Misc Acc] => hello
    [Misc Acc Desc] => world
)

UPDATE

正如我在评论中提到(后查明是HTML)。您可以使用DOM解析器。我有在过去使用的是PHPQuery它现在有点过时。但是,这是不错的,因为你可以使用jQuery语法。例如说,你有这

<ul id="title" >
    <li>header</li>
    <li>header</li>
    <li>header</li>
</ul>

你可以像这样的东西(它已经有一段时间,因此,如果这是错误抱歉)发现

  $length =  $PHPQuery->find("#headers li")->lenght;

   for($i=0;$i<$lenght;++$i){
      echo $PHPQuery->find("#headers li:eq($i)")->text();
   }

你甚至可以使用->attr('href')例如拉属性。基本上,你可以把HTML结构的优势,拉你需要的不是转换成文本并试图删除了一堆的“东西”是什么

干杯!

© www.soinside.com 2019 - 2024. All rights reserved.