發現我有這個內容的文件:查找特定行,如果文本從外部文件
Line A
Line B
Line C
Line D
Line E
如果我在尋找Line C
,我怎樣可以得到包含Line C
爲row 2
該行的結果呢?我用的是file_get_contents()
語法如下:
$get_file=file_get_contents("text.txt");
substr_count($get_file, "Line C");
但結果是1
。
發現我有這個內容的文件:查找特定行,如果文本從外部文件
Line A
Line B
Line C
Line D
Line E
如果我在尋找Line C
,我怎樣可以得到包含Line C
爲row 2
該行的結果呢?我用的是file_get_contents()
語法如下:
$get_file=file_get_contents("text.txt");
substr_count($get_file, "Line C");
但結果是1
。
我測試這樣的,它返回「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 ?>
謝謝,但它沒有顯示任何東西。我努力了。 –
是的,謝謝。我測試這樣並返回'2'。但是,對我來說這是不可能的,因爲我使用file_get_contents()作爲變量$ str,而不是像上面那樣的字符串。 –
您可以使用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
到目前爲止您嘗試過什麼? – Thamilan
使用$ get_file = file_get_contents(「text.txt」)從文本獲取內容,所以我使用substr_count($ get_file,「Line C」)計算行數。但結果顯示第一(1)。 –