让我们考虑一下有一个名为1.txt的文本文件,它具有以下内容。
wow<br>wow<br>wow<!--Read More--><br>wow<br>wow<br>wow<br>wow<br>wow<br>wow<br>
我只想在<!--Read More-->
之前显示其内容目前正在使用fopen命令读取和显示整个文本文件。
$file_handle = fopen("posts/1.txt", "r");
while (!feof($file_handle)) {
$line_of_text = fgets($file_handle);
print $line_of_text;
}
请有人帮我做这个。。。
$file_handle = fopen("posts/1.txt", "r");
while ((!feof($file_handle) && (($line_of_text = fgets($file_handle)) != "<!--Read More-->"))
{
print $line_of_text;
}
警告:只有当您的"停止文本"总是在同一行上时,这才有效
您可以使用strstr()函数来检查您读取的行是否包含要停止的字符串。
如果搜索到的字符串不在行中,则以您的行作为第一个参数、以搜索到的串作为第二个参数和以true
作为第三个参数调用它将返回false
,或者它将返回行中在搜索到字符串之前的部分。
$file_handle = fopen("posts/1.txt", "r");
while (!feof($file_handle)) {
/* Retrieve a line */
$line_of_text = fgets($file_handle);
/* Check if the stop text is in the line. If no returns false
else return the part of the string before the stop text */
$ret = strstr($line_of_text, "<!--Read More-->", true);
/* If stop text not found, print the line else print only the beginning */
if (false === $ret) {
print $line_of_text;
} else {
print $ret;
break;
}
}