1 回答

TA貢獻(xiàn)1875條經(jīng)驗(yàn) 獲得超3個(gè)贊
例子:
<?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>';
}
輸入文件內(nèi)容:
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鍵包含您當(dāng)前正在閱讀的行索引,并且$line是當(dāng)前行的字符串。explode 函數(shù)將從 0 開始索引您的數(shù)組,因此當(dāng)您讀取它時(shí)第一行索引將為 0。這就是這一行中的 + 1 的原因:$results[] = ($lineNumber + 1) .":{$line}";
您if (strpos($line, $desiredWord) !== false)正在檢查是否在給定行中找到所需的單詞。如果你只想要一個(gè)結(jié)果,你可以在這里返回,但如果你想收集所有可以找到這個(gè)詞的行,那么你可以像這樣將找到的行存儲(chǔ)在$results
最后,您可以使用第二個(gè) foreach 或任何其他方式檢查結(jié)果 - 取決于您的實(shí)施。
- 1 回答
- 0 關(guān)注
- 94 瀏覽
添加回答
舉報(bào)