English 中文(简体)
从阵列的开始和结束到三重空白线的最快途径是什么?
原标题:What is the fastest way to trim blank lines from beginning and end of array?

原文:

<?php

$lines[] =   ;
$lines[] =  first line    ;
$lines[] =  second line  ;
$lines[] =   ;
$lines[] =  fourth line ;
$lines[] =   ;
$lines[] =   ;

$lineCount = 1;
foreach($lines as $line) {
    echo $lineCount .  : [  . trim($line) .  ]<br/> ; 
    $lineCount++;
}

?>

产出:

1: []
2: [first line]
3: [second line]
4: []
5: [fourth line]
6: []
7: []

改变上述文字的最快、最有效的方式是删除preceding<>/strong>和 trailing 空白条目,但不是内幕。 a. 空白条目,以便产出:

1: [first line]
2: [second line]
3: []
4: [fourth line]

我可以使用海滩通道,但我想象,有一阵列——过滤器或类似装置,效率更高。

最佳回答

为创建三毫米阵列,有<条码>。

function trimLines($lines) {
    $end = count($lines);
    for ($start=0; $lines[$start] ===   ; ++$start) {
        if ($start == $end) {
            return array();
        }
    }
    do { --$end; } while ($lines[$end] ===   );
    return array_slice($lines, $start, $end-$start+1);
}
问题回答
// find the first non-blank line
$size = count($lines);
while ($lines[$i] ===    && $i < $size) {
  $i++;
}
$start = $i;

// find the last non-blank line
$i = $size;
while ($lines[$i - 1] ===    && $i > $start) {
  $i--;
}
$end = $i;

// traverse between the two    
for ($i=$start; $i<$end; $i++) {
  echo ($i + $start) .  : [  . trim($lines[$i]) .  ]<br/> ;
}




相关问题
Simple JAVA: Password Verifier problem

I have a simple problem that says: A password for xyz corporation is supposed to be 6 characters long and made up of a combination of letters and digits. Write a program fragment to read in a string ...

Case insensitive comparison of strings in shell script

The == operator is used to compare two strings in shell script. However, I want to compare two strings ignoring case, how can it be done? Is there any standard command for this?

Trying to split by two delimiters and it doesn t work - C

I wrote below code to readin line by line from stdin ex. city=Boston;city=New York;city=Chicago and then split each line by ; delimiter and print each record. Then in yet another loop I try to ...

String initialization with pair of iterators

I m trying to initialize string with iterators and something like this works: ifstream fin("tmp.txt"); istream_iterator<char> in_i(fin), eos; //here eos is 1 over the end string s(in_i, ...

break a string in parts

I have a string "pc1|pc2|pc3|" I want to get each word on different line like: pc1 pc2 pc3 I need to do this in C#... any suggestions??

Quick padding of a string in Delphi

I was trying to speed up a certain routine in an application, and my profiler, AQTime, identified one method in particular as a bottleneck. The method has been with us for years, and is part of a "...