php - 在文件中查找一个单词,然后将接下来的 10 个值放入数组中

标签 php arrays for-loop

我有一个文本文件,我想在第一次看到特定单词时将 10 个值放入数组中。让我们假设文本包含:

...,sometext,moretext,wordddddd,867767,3468647,sometext,...

我想将单词 worddddddd 后的前 10 个值放入数组中, 即 array[0] 将是 867767array[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/

相关文章:

android - 每轮for循环的不同图像

java基本数组问题

python - 查找字符串中字符的所有位置

php - 0 当没有行存在时

php - Mysql AND WHERE 选择

无法读取c中数组的第一个字符

Java多客户端聊天应用程序-发送消息问题

php - 将 MySQL 查询结果与数组进行比较

javascript - 使用带有 smtp 身份验证的电子邮件表单提交时出现问题

c - C中二维字符数组的行数