Php和javascript数组-跳过空白值并添加到新数组中


Php and javascript array - skipping blank values and adding to new array?

我在php中有一个数组,它包含文本文件的所有行(每行是数组的一个值)。我的文本文件有空行,所以数组也有空行。我想在数组中搜索一个特定的值,如下所示:

$array = array();
        $lines = file("textfile.txt"); //file in to an array
        foreach ($lines as $line)
        {
            if (stripos($line, "$$") !== false) 
            {
                $array[] = str_replace("$$", "", $line);
            }
        }

上面的代码正在搜索$$并将其替换为空白。文本文件包含一行$$1或任何数字,我希望它能找到该行的所有实例,它正在这样做。

我的问题是,我希望它在找到$$(数字)后找到接下来的5行,并将它们放入多维数组中。多维数组看起来与此类似(该程序是一个测试,以防您想知道为什么数组的命名方式):

$test = array(
    array('question' => 'What is the answer', 'ansa' => "answerswera", 'ansb' => "answerswerb", 'ansc' => "answerswerc", 'ansd' => "answerswerd"), // $test[1]
    array('question' => 'What is the answer', 'ansa' => "answerswera", 'ansb' => "answerswerb", 'ansc' => "answerswerc", 'ansd' => "answerswerd"), // $test[2]
);

$$(数字)后面的五行是一个问题和四个答案,需要进入数组。我使用regxp和搜索的代码不起作用,所以我放弃了它。

您可以尝试这样的方法。。。

<?php
$lines = array_filter(file('text.txt')); //file in to an array
$questions = array();
// find your starts and pull out questions
foreach ($lines as $k=>$line)
{
    if (stripos($line, "$$") !== false) 
    {
        $questions[] =  array_slice($lines, $k, 5);
    }
}

// dump
var_dump($questions);

请参阅php手册了解array_slice

您看过preg_replace_callback吗?

沿着这些路线的一些东西应该起作用:

<?php
function replace_callback($matches) {
    var_dump($matches);
}
preg_replace_callback('/'$'$[0-9]+'s+([^'.PHP_EOL.']+){5}/is', 'replace_callback', file_get_contents('textfile.txt'));
?>