Как файл можно разбить на массив, сравнить с запросом, а затем распечатать в контексте? - PullRequest
0 голосов
/ 04 ноября 2019

все. Я пытаюсь загрузить файл как массив, разбитый на разрывы строк, а затем распечатать строки, содержащие запрос, в дополнение к следующим двум строкам. Однако всякий раз, когда я пытаюсь запустить его, он всегда прибегает к моему оператору 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";

}

1 Ответ

1 голос
/ 04 ноября 2019

При воспроизведении с этим кодом единственный способ, которым он может работать, - это если любая строка содержит слово «текст» и только слово «текст». Попробуйте это:

$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";
}
...