我有一个程序,搜索文本文件,看看是否有一个特定的字符串在该文件,我已经得到正常工作。我需要知道的是如何打印该文本文件的特定行。例如,如果文件在自己的行中列出了三个街道名称,并且程序搜索其中一个,我希望它只打印出具有该街道名称的行。如何打印文本文件的特定行?
如果该文件是这样的:与被搜索的词是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.
}
你可以使用正则表达式。也许像https://regex101.com/r/xwzlgZ/2/...这样的东西,或者你可以使用'strpos'和'substr',但是你不知道它是否与它部分匹配。 – chris85