2017-02-26 33 views
-1

發現我有這個內容的文件:查找特定行,如果文本從外部文件

Line A 
Line B 
Line C 
Line D 
Line E 

如果我在尋找Line C,我怎樣可以得到包含Line Crow 2該行的結果呢?我用的是file_get_contents()語法如下:

$get_file=file_get_contents("text.txt"); 
substr_count($get_file, "Line C"); 

但結果是1

+0

到目前爲止您嘗試過什麼? – Thamilan

+0

使用$ get_file = file_get_contents(「text.txt」)從文本獲取內容,所以我使用substr_count($ get_file,「Line C」)計算行數。但結果顯示第一(1)。 –

回答

0

我測試這樣的,它返回「2」

1 <?php 
2 $str = "Line A\nLine B\nLine C\nLine D\nLine E\n"; 
3 $arr = explode("\n", $str); 
4 $key = array_search("Line C", $arr); 
5 if ($key !== false) 
6 { 
7  echo $key; 
8 } 
9 ?> 
+0

謝謝,但它沒有顯示任何東西。我努力了。 –

+0

是的,謝謝。我測試這樣並返回'2'。但是,對我來說這是不可能的,因爲我使用file_get_contents()作爲變量$ str,而不是像上面那樣的字符串。 –

0

您可以使用strstr搜索字符串之前獲取內容。使用substr_count您可以找到事件。

$search = 'Line C'; 

$content = file_get_contents('example.txt'); 

$preceedingContents = strstr($content, $search, true); 

if ($preceedingContents !== false) { 
    $line = substr_count($preceedingContents, PHP_EOL); 
    echo "$search found in row : $line"; 
} else { 
    echo "$search not found"; 
} 

如果您example.txt包含:

Line A 
Line B 
Line C 
Line D 
Line E 

給出:

因爲,$search = 'Line C';Line C found in row : 2
因爲,$search = 'Line A';Line C found in row : 0
因爲,$search = 'Line R';Line R not found

相關問題