2012-12-04 19 views
0

我需要一個腳本來統計文本文件中所有位於同一行上的管道分隔條目的數量。我發現了一個腳本,它可以對線條進行計算並對其進行修改,認爲我可能會將其運行起來,但可悲的是,它仍然計算線條,因此目前推算出值1.請您可以看看並幫助我解決問題嗎?該文本文件看起來是這樣的:PHP計算文本文件中所有位於同一行上的分隔值

Fred|Keith|Steve|James 

我試圖腳本是這樣的:

$file1 = "names.txt"; 
$line = file($file1); 
$count = count(explode("|", $line)); 
echo "$file1 contains $count words"; 

任何援助深表感謝。 非常感謝。

+0

這是一個重新發布的話?我似乎記得以前看過這個確切的問題。同樣的錯誤:「putputs」 –

回答

1

最快的方法就是計數管,並添加一個。修剪字符串以確保開頭和結尾處的管道不計爲項目。

<?php 
    $contents = file_get_contents('names.txt'); 
    $count = substr_count(trim($contents, "|\n "), '|') + 1; 
    echo "$file1 contains $count words"; 
+0

這非常有效 - 非常感謝! – Martyn

1

有多種方法來解決這個問題,打開文件的方式不同,以及解釋數據的不同方式。

但是,你要尋找與此類似:

<?php 
    $data = file_get_contents("names.txt"); 
    $count = count(preg_split("/|/", $data)); 
    echo "The file contains $count words."; 
?> 
1

很多方法可以做到這一點,這是我拿......

// get lines as array from file 
$lines = file('names.txt'); 

// get a count for the number of words on each line (PHP > 5.3) 
$counts = array_map(function($line) { return count(explode('|', $line)); }, $lines); 
// OR (PHP < 5.3) get a count for the number of words on each line (PHP < 5.3) 
//$counts = array_map(create_function('$line', 'return count(explode("|", $line));'), $lines); 

// get the sum of all counts 
$count = array_sum($counts); 

// putting it all together as a one liner (PHP > 5.3)... 
$count = array_sum(array_map(function($line) { return count(explode('|', $line)); }, file('names.txt'))); 
// or (PHP < 5.3)... 
// $count = array_sum(array_map(create_function('$line', 'return count(explode("|", $line));'), file('names.txt'))); 
0

你幾乎做到了,有的只是如何file作品小誤會:

你沒有單行但所有行中行變量,您可以訪問一個單一行的數字索引從0開始

$nunWords = count(explode ('|', $line[0])); 

所以指望,讓我們說10號線,你會簡單地改變指數9(因爲我們從0開始)

又如

$lines = file ('yourfile'); 
foreach ($lines as $curLine => $line) 
{ 
     echo "On line " . $curLine+1 . " we got " . count(explode ('|', $line)) . " words<br/>\n"; 
} 
相關問題