【问题标题】:What is the fastest way to trim blank lines from beginning and end of array?从数组的开头和结尾修剪空白行的最快方法是什么?
【发布时间】:2010-05-02 10:44:01
【问题描述】:

这个脚本:

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

什么是更改上述脚本的最快、最有效的方法,以便它同时删除 precedingtrailing 空白条目,但 不是内部 strong> 空白条目,以便输出:

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

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

【问题讨论】:

    标签: php string arrays trim


    【解决方案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);
    }
    

    【讨论】:

      【解决方案2】:
      // 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/>';
      }
      

      【讨论】:

        猜你喜欢
        • 2011-03-01
        • 2015-02-06
        • 1970-01-01
        • 2023-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-04
        • 1970-01-01
        相关资源
        最近更新 更多