PHP字符串上的多个substr

时间:2018-09-05 01:06:14

标签: php substr

我有一个要为其提供字符串索引的字符串。

我正在创建一个读取它的过程,并且想知道是否存在一个我忽略了的php函数,或者不知道是否更容易执行此过程。

$ data:

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行,并使其可移植到任意数量的fieldIndex中? >

所需结果:

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

    )
)                      

2 个答案:

答案 0 :(得分: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.....................................
)

答案 1 :(得分: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,另一个星期一。

更新

您也可以使用文件流打包程序来修复用于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
)

更新

正如我在评论中提到的(发现它是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结构并提取所需的内容,而不是将其转换为文本并尝试删除一堆“东西”

干杯!