在 PHP 文件中查找一行
这个循环似乎没有找到我想要的行(实际上它根本没有找到任何东西)。
$file_lines = file("rss.xml");
$max_lines = count($file_lines);
$id = $_POST['id_number'];
$start_string = " <!--".$id."-->";
$start_line;
$end_string = "<!--end of item ".$id."-->";
$end_line;
for ($i = 0; $i < $max_lines; $i++) {
$temp_line = $file_lines[$i];
if ($temp_line == $start_string) {
$start_line = $i;
echo "found start";
}
if ($temp_line == $end_string) {
$end_line = $i;
echo "found end";
}
}
它应该逐行浏览文件并查看它是否与预设字符串匹配。如果是,则应该将变量设置为该行的位置(计数器 $i)。
This loop doesn't seem to be finding the lines I want it to (it's not finding anything at all actually).
$file_lines = file("rss.xml");
$max_lines = count($file_lines);
$id = $_POST['id_number'];
$start_string = " <!--".$id."-->";
$start_line;
$end_string = "<!--end of item ".$id."-->";
$end_line;
for ($i = 0; $i < $max_lines; $i++) {
$temp_line = $file_lines[$i];
if ($temp_line == $start_string) {
$start_line = $i;
echo "found start";
}
if ($temp_line == $end_string) {
$end_line = $i;
echo "found end";
}
}
It's supposed to be going through a file line-by-line and looking to see if it matches a preset string. If it does, it is supposed to set a variable to the position of the line (the counter $i).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一个选项是使用 array_search:
$index
将是找到的元素(如果有)的键。您可以通过检查 false 来检查是否获得结果:
如下所述,文件不会修剪行结尾。您可以使用 FILE_IGNORE_NEW_LINES 标志来跳过此操作:
An option is to use array_search:
$index
will be the key of your found element, if any.You can check if you have got a result by checking for false:
As mentioned below, file does not trim line endings. You can use the
FILE_IGNORE_NEW_LINES
flag to skip this:只是瞎猜,但输入文件可能包含行尾字符(例如
\n
),这可能会导致使用==
的比较失败。尝试使用诸如strpos
之类的函数。Just a shot in the dark, but the input file may contain end-of-line characters (e.g.
\n
), which may throw off your comparison using==
. Try using a function such asstrpos
.< 之前有一个空格在那条线上。我不知道它是否应该存在,但如果它不在输入文件中,很容易导致意外结果。
You have a space before the < in that line. I don't know if that's supposed to be there, but it could easily cause unexpected results if it's not in the input file.