[英]How do I get a line of a text file with the line number in PHP?
我已經嘗試過了,但是我不知道為什么它不起作用:
<?php
$roomid = $_GET["roomid"];
$file = fopen('Rooms//testid.txt','a+');
$lines = file('Rooms//testid.txt');
$search = $roomid;
$line_number = false;
while (list($key, $line) = each($lines) and !$line_number) {
$line_number = (strpos($line, $search) !== FALSE) ? $key + 1 : $line_number;
}
echo "<script type='text/javascript'>alert('$lines[$line_number]');</script>";
?>
循環過於復雜。 您不需要行號,只需行。 您可以使用布爾變量來確定是否找到了搜索字符串,並可以使用break
語句來結束循環,而不是使用復雜的while
條件。
另外,由於將$key + 1
分配給$line_number
,索引也減少了1。
$found = false;
foreach ($lines as $line) {
if (strpos($line, $search) !== FALSE) {
$found = true;
break;
}
}
if ($found) {
echo "<script type='text/javascript'>alert('$line');</script>";
} else {
echo "<script type='text/javascript'>alert('$roomid not found');</script>";
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.