我有一个文本文件,我想在第一次看到特定单词时将 10 个值放入数组中。让我们假设文本包含:
...,sometext,moretext,wordddddd,867767,3468647,sometext,...
我想将单词 worddddddd
后的前 10 个值放入数组中,
即 array[0]
将是 867767
而 array[1]
将是 34686
等等。我不需要数组中的逗号,语言是 PHP。
在我的尝试中,我尝试扫描整个文件,如果我看到单词 wordddddd
然后执行 for
循环,该循环将迭代 10 次以填充数组中的前 10 个位置。我使用 explode
从逗号中拆分单词。
我标记了错误所在的行 我怎样才能做到这一点?请一些 PHP 专家?这是我的尝试:
<?php
$id='wordddddd';
$handle = fopen('file.txt', 'r');
$valid = false; // init as false
$arr=explode(",", $handle);// ERROR IN THIS LINE Warning: explode() expects parameter 2 to be string, resource given in
while (($buffer = fgets($handle)) !== false) {
if (strpos($buffer, $id) !== false) {
$valid = TRUE;
$pos=strpos($buffer, $id);
echo 'Its there in pos ',$pos;
for($x=0;$x<=10;$x++){
echo $valid[$x+$pos+1];
}
break; // Once you find the string, you should break out the loop.
}
}
fclose($handle);
?>
最佳答案
$your_word = 'wordddddd';
$number_of_items_to_limit = 10;
$array = explode(",", file_get_contents('text.txt')); //Explode file content by ","
$found = false; //Set dafault value for key word flag to false
$array = array_filter( // remove all items without found flag
$array,
function($value) use (&$found,&$your_word) {
if($value == $your_word) {
$found = true; // set flag to found
}
if($found) {
return true ; //return items that are coming after the flag
} else {
return false;
}
});
$result = array_slice($array, 0, $number_of_items_to_limit); // return only first 10 items from array
关于php - 在文件中查找一个单词,然后将接下来的 10 个值放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46136326/