challenge 条件を満たす行を取り除く

ファイルから1行ずつ読み込み、"#"で始まる行だけを取り除いてファイルに出力するコードを書いてください。

サンプル入力

hello!
# remove this
 # don't remove this
bye!
サンプル出力
hello!
 # don't remove this
bye!

Posted feedbacks - PHP

PHP4以下なら普通にfopenとかで
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<?php
function removeComment($infile, $outfile, $startwith ='#') {
    $r = "";
    foreach(file($infile) as $line) {
        if (strncmp($line, $startwith, strlen($startwith))) {
            $r .= $line;
        }
    }
    file_put_contents($outfile, $r);
}

これはひどい
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
$handle = fopen('hoge.txt','r');
while(!feof($handle)){
	$buffer = fgets($handle);
	if(substr($buffer,0,1) != '#'){
		$array[] = $buffer;
	}
}
fclose($handle);
file_put_contents('hoge.txt',$array)
?>

stream_get_lineバージョン
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<?php

$handle = fopen("odai10.txt", "r");
while(!feof($handle))
{
    $buffer = stream_get_line($handle, 4096, "\n");
    if(strpos($buffer, "#") !== 0 )
    {
        $array[] = $buffer;
    }
}
fclose($handle);
file_put_contents("odai10.txt", implode("\n", $array));
?>

とにかく短く書いてみた。

>php sample.php src.txt dest.txt
1
2
3
<?php
foreach(file($argv[1]) as $l)if(strpos($l,"#") !== 0)$r[]=$l;
file_put_contents($argv[2],implode("",$r));

Index

Feed

Other

Link

Pathtraq

loading...