1 回答

TA貢獻1875條經驗 獲得超3個贊
例子:
<?php
$desiredWord = 'apple';
$fileString = file_get_contents('asd.txt');
$lines = explode(PHP_EOL, $fileString);
$results = [];
foreach ($lines as $lineNumber => $line) {
if (strpos($line, $desiredWord) !== false) {
$results[] = ($lineNumber + 1) .":{$line}";
}
}
foreach ($results as $result) {
echo '<pre>' . print_r($result, true) . '</pre>';
}
輸入文件內容:
apple
asdfsdf
vs
werwerwer
llll
hhheeheh
there is an apple on the tree
the tree does not fall far from it's apple
輸出:
1:apple
7:there is an apple on the tree
8:the tree does not fall far from it's apple
您可以使用 foreach 遍歷這些行。該$lineNumber鍵包含您當前正在閱讀的行索引,并且$line是當前行的字符串。explode 函數將從 0 開始索引您的數組,因此當您讀取它時第一行索引將為 0。這就是這一行中的 + 1 的原因:$results[] = ($lineNumber + 1) .":{$line}";
您if (strpos($line, $desiredWord) !== false)正在檢查是否在給定行中找到所需的單詞。如果你只想要一個結果,你可以在這里返回,但如果你想收集所有可以找到這個詞的行,那么你可以像這樣將找到的行存儲在$results
最后,您可以使用第二個 foreach 或任何其他方式檢查結果 - 取決于您的實施。
- 1 回答
- 0 關注
- 96 瀏覽
添加回答
舉報