全部。我正在尝试将文件加载为在换行符处以数组拆分的形式,然后打印除以下两行以外的包含查询的行。但是,无论何时我尝试运行它,即使我知道可以在该特定文件中找到查询,它也总是使用我的else语句。这使我相信存在编码问题,因此我需要您的帮助。预先谢谢!
$query = "text";
// reads file into array and splits at line breaks
$array = explode("\n", file_get_contents('files/file2.txt'));
// checks to see if the query is found in the array
// checks if the value of at least one key matches the query
// and, if so, prints the line and next two
if (in_array($query, $array)) {
foreach ($array as $key => $value) {
if($value == $search AND $count >= $key+3) {
echo $array[$key] . $array[$key+1] . $array[$key+2];
}
}
} else {
echo "Match not found.\n";
[使用此代码时,唯一可行的方法是,如果任何一行包含单词“ text”且仅包含单词“ text”。试试这个:
$query = "text";
// reads file into array and splits at line breaks
$array = explode("\n", file_get_contents('files/file2.txt'));
// checks to see if the query is found in the array
// checks if the value of at least one key matches the query
// and, if so, prints the line and next two
$found = false;
// Here's where I made some changes.
// I added a new foreach loop to go through each line in the array.
foreach ($array as $x) {
// Instead of using the in_array function, I simply searched for
// the position of the query. If the strpos function returns -1,
// it means that the query hasn't been found.
if (strpos($x, $query) > -1) {
// If found, set the found flag as true.
$found = true;
foreach ($array as $key => $value) {
if($value == $search AND $count >= $key+3) {
echo $array[$key] . $array[$key+1] . $array[$key+2];
}
}
}
}
// If the found flag is false, display the "Match not found" message.
if ($found) {} else {
echo "Match not found.\n";
}