如何从文件中读取行,只显示某些行?

时间:2014-05-02 12:42:30

标签: php arrays function file-io

以下是我档案的一部分:

nid: 4645867: Title
nid: 4645887: Metropolitan Afternoon
     oid: 4645888 | 35 x 38
     fid: 190035 | filepath: /var/storage/files/drupal/2e1a91af45d12ff9fb1b2231f88b7029.jpg
nid: 4645893: Fleurs du Matin II
     oid: 4645894 | 22 x 28
     fid: 190038 | filepath: /var/storage/files/drupal/d5e745715e21f649ff3fd8b3418581d9.jpg
nid: 4645913: Fleurs du Matin I
     oid: 4645914 | 22 x 28
     fid: 190045 | filepath: /var/storage/files/drupal/2f05f2c8e79997510d3f7f5a2cd28392.jpg

我只想显示以" nid"。

开头的行

这是我的代码:

function tf_batch_view_deleted_items()
{

  $handle = fopen("/data/www/content/importTemp/delete_posters - ico.htm", "r");
  if ($handle) 
  {
    while (($line = fgets($handle)) !== false) 
    {
      if (tf_common_contains($line, "nid"))
      {
        echo $line;
      }
    }
  } 
  else 
  {
    echo "error opening the file.";
  } 
  fclose($handle);
}

function tf_common_contains($haystack, $needle)
{
  $pos = strpos($haystack, $needle);

  if ($pos === FALSE)
  {
    return FALSE;
  }
  else
  {
    return TRUE;
  }
}

编辑:该文件似乎全部在一行。

6 个答案:

答案 0 :(得分:2)

也许使用正则表达式会:

function tf_batch_view_deleted_items()
{

$handle = file_gets_content("/data/www/content/importTemp/delete_posters - ico.htm");

if ($handle !== "") 
{
    preg_match_all('/^nid:.*$/m', $handle, $match);
    foreach($match[0] as $line){
        echo $line;
    }
} 
else 
{
    echo "error opening the file.";
} 
}

示例:http://sandbox.onlinephpfunctions.com/code/c1a1473fae77454d0e0d5f09b6c305111eaa6ee6

答案 1 :(得分:1)

一衬垫..

<?php

function tf_batch_view_deleted_items()
{

$arr = array_filter(array_map(function($v){  if(stripos($v,'nid:')!==false){ return $v;}},file('/data/www/content/importTemp/delete_posters - ico.htm',FILE_IGNORE_NEW_LINES)));
print_r($arr);

}

 tf_batch_view_deleted_items(); //<====== Call like this !!!

<强> OUTPUT:

Array
(
    [0] => nid: 4645867: Title
    [1] => nid: 4645887: Metropolitan Afternoon
    [4] => nid: 4645893: Fleurs du Matin II
    [7] => nid: 4645913: Fleurs du Matin I
)

答案 2 :(得分:0)

if ($pos === 0) {
    return TRUE;
} else {
    return FALSE;
}

答案 3 :(得分:0)

$lines = file("abx.txt");
foreach($lines as $line){
if(substr($line, 0, 2) == "nid") echo $line;
}

答案 4 :(得分:0)

你走了:

<?php
$handle = fopen("test.txt", "r");
if ($handle) {
    while (($line = fgets($handle)) !== false) {
        $line = trim($line);
        $prefix = substr($line,0,3);

        if(strcasecmp($prefix,'nid') == 0) {
            echo $line.'<br />';
        }
    }
} else {
    echo 'Could not find file!';
} 
fclose($handle);

&GT;

答案 5 :(得分:0)

将html文件转换为文本文件后,我的代码工作正常。谢谢你的帮助。