[英]How Do You Print A Specific Line Of A Text File?
我有一個搜索文本文件的程序,以查看該文件中是否有特定的字符串,我已經可以正常工作了。 我需要知道的是如何打印該文本文件的特定行。 例如,如果文件在其自己的行上列出了三個街道名稱,並且程序搜索了其中一個,則我希望它僅打印出具有該街道名稱的行。
如果文件看起來像這樣:並且搜索的單詞是Rose Road
,我希望它僅打印出6784 Rose Road
4543 Drock Drive
1254 HeadHill Road
6784 Rose Road
到目前為止,這就是我要檢查的文件中的內容,但是我不確定如何打印出特定的行。
$roadName = "Rose";
$handle = fopen("streets.txt", "r");
if(strpos(file_get_contents("streets.txt"),$roadName) !== false) //Checks to make sure its in the file.
{
echo fgets($handle); //This is what I was trying, but it only prints the 1st line.
}
file_get_contents
和strpos
對文件句柄沒有影響,因此fgets
只是從文件開頭讀取。
您可以使用fgets
讀取每一行,測試它是否與字符串匹配,然后打印出來。
while ($line = fgets($handler)) {
if (strpos($line, $roadName) !== false) {
echo $line;
break;
}
}
如果文件很大,這比使用file_get_contents
的解決方案要好,因為它不必將整個文件讀入內存,然后創建所有行的巨大數組。
我將這些行分解成一個數組,然后檢查每一行:
$roadName = "Rose";
$file=file_get_contents("streets.txt")
if(strpos($file,$roadName) !== false) //Checks to make sure its in the file.
{
$lines = explode(PHP_EOL,$file);
foreach($lines as $line) {
if (strpos($line,$roadName) !== false) echo($line);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.