在文件中查找单词,然后将下10个值放入数组中

时间:2017-09-10 00:43:37

标签: php arrays for-loop

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

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

我希望将单词wordddddd后面的前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);
    ?>

4 个答案:

答案 0 :(得分:2)

    $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

答案 1 :(得分:2)

尝试使用fgetcsv。它会为您节省explode的通话费用。 以下是手册页中的示例:

$row = 1;
if (($handle = fopen("test.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
    }
    fclose($handle);
}

答案 2 :(得分:1)

$id='wordddddd';
$fopen = fopen("file.txt", 'r');
$content= htmlspecialchars(file_get_contents("file.txt"));//
$split=explode(",", $content);
$arr_len=count($split);
$pos=0;
$result=array();

//finding the position of the word in the array
foreach ($split as $x){
    if(stripos($id, $x)!==false) {
    break;}
    $pos++;
}

for($x=0;$x<10;$x++){
    $result[$x]=$split[$pos+1];
    $pos++;
}

答案 3 :(得分:0)

您需要使用$ handle变量逐行读取文件并将其作为数组。 然后你需要匹配$ id值。 错误是因为explode()不适用于$ handle,而是适用于非大小写的字符串变量。

相关问题