0

这个脚本:

<?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: []

更改上述脚本的最快,最有效的方法是什么,以便它还删除前面后面的空白条目,但不删除内部空白条目,以便输出以下内容:

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

我可以使用 foreach 循环,但我想有一种方法可以使用 array_filter 或类似的方法,效率更高。

4

2 回答 2

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/>';
}
于 2010-05-02T10:48:46.150 回答
1

array_slice创建修剪后的数组。

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);
}
于 2010-05-02T11:00:16.280 回答