使用php从文本文件中过滤数据

时间:2015-10-11 02:08:36

标签: php text-files

这基本上就是我所拥有的:

$pieces[4]

代码并没有在这里结束,但我希望到目前为止有意义。

我需要的是仅回显那些具有特定值{ $element = trim($element); if (strpos($element,'food') !== false) { $pieces = explode("|", $element); } 的行。假设 - 仅回显文本文件中具有2015-10-05|21:31|name1|name2|food|comment|extra - needs to trigger echo 2015-10-05|21:31|name1|name2|health|comment|extra - needs to skip 2015-10-05|21:31|name1|name2|food|comment|extra - needs to trigger echo 2015-10-05|21:31|name1|name2|finance|comment|extra - needs to skip 2015-10-05|21:31|name1|name2|finance|comment|extra - needs to skip 2015-10-05|21:31|name1|name2|health|comment|extra - needs to skip 2015-10-05|21:31|name1|name2|food|comment|extra - needs to trigger echo 值“食物”的那些行。

有可能吗?我尝试了数组搜索,数组键,过滤数组等...但我从来没有做对。

更新: 佩德罗的回答(中途):

$pieces[4]

有点工作 - 它完成了这项工作,但将那些我要隐藏的输出替换为那些被过滤掉的输出。

我想要的是跳过不包含给定值的输出。此时它会跳过不需要的输出,但会替换那些带有空白值的输出,或者只是将过滤后的输出相乘。下面是关于回声需要哪些行以及要跳过哪些行的说明。

20xx

上面的代码现在是:

  1. 正确输出

  2. 输出已替换(与输出1相同) - 需要跳过

  3. 正确输出

  4. 输出已替换(与输出3相同) - 需要跳过

  5. 输出已替换(与输出3相同) - 需要跳过

  6. 输出已替换(与输出3相同) - 需要跳过

  7. 正确输出

  8. 因此,它设法过滤掉我需要的东西,但那些与标准不匹配的东西只是被最后一个匹配的行所取代。但我需要跳过那些。

    唯一缺少的是补充Pedro上面的答案,以便跳过(忽略不符合标准// Parse String representation. String input = "23-May-12"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern ( "d-MMMM-yy" , Locale.ENGLISH ); // Using four "M" characters means we expect the full name of the month. LocalDate localDate = formatter.parse ( input , LocalDate :: from ); =“食物”)2,4,5,6的行,忽略根本没有回应。

2 个答案:

答案 0 :(得分:0)

您可以使用strpos检查该行是否包含单词food

$element = trim($element);
if (strpos($element,'food') !== false) {
    $pieces = explode("|", $element);
    //the rest of the code
}

答案 1 :(得分:0)

我对佩德罗的回答做了一些调整,我想我得到了我需要的结果。代码是这样的:

<?php
$data = file('../articles.txt');

$data=str_replace(array('<', '>', '\\', '/', '='), "", $data);
foreach($data as $element) 
{
$element = trim($element);
if (strpos($element,'food') !== false) {
$pieces = explode("|", $element);
echo "

这里的一些HTML和PHP不需要任何调整。

";    
}
else {
echo "";
}
}
?>

起初我添加了echo“error”;到其他部分,但它只是为了测试。我只是通过删除它来获得令人不安的错误消息。目前它看起来像是那样工作。

如果我不添加其他部分,那么我回到了它过滤掉其中有“食物”值的行的问题,但是这次只回零其他所有内容。