如何使用php从文本文件中获取列

如何使用php从文本文件中获取列,php,csv,Php,Csv,我想选择文本文件的特定列。我正在使用PHP。该文件的内容是 F: TC# Alpha 1 A Z F: TC# Alpha 2 A Z F: TC# Alpha 3 A Z F: TC# Alpha 1 0

我想选择文本文件的特定列。我正在使用PHP。该文件的内容是

F: TC#              Alpha      1 A                   Z  
F: TC#              Alpha      2 A                   Z  
F: TC#              Alpha      3 A                   Z  
F: TC#              Alpha      1 0                   3   

现在我想选择包含内容3 A的整个列。我如何使用PHP实现它?

您的文件以空格分隔?只需使用
explode()

您可以合并和(以防该文件中有许多行)


如果您只想在一行中选择字符串
3 A
,可以执行以下操作:

$search = "3 A";
$matches = array();
$fp = fopen("file.txt", "r");
while (!feof($fp)) {
  $line = fgets($fp, 4096);
  if (strpos($line, $search) !== false) {
    $matches[] = $line;
  }
}
print_r($matches); // voila
如果
3a
的出现必须在特定的列中,那么事情就变得更加复杂了。您必须将每一行(“行”)拆分为一个数组,该数组包含每个“列”的一个元素

您可以通过按空格字符(或制表符?文件看起来如何?)分解字符串来执行此操作,但这可能是错误的。当
3 A
包含在单个“列”中时,它将出现故障

如果它是一个固定宽度的表(您的示例如图所示),请找到每个字段的长度,并将行切分。 例如:

根据实际表格布局进行调整。例如,如果
3
A
代表不同的列,则进行以下更改:

// how long is each field?
$field_legths = array(20, 11, 2, 20, 3);

$conditions = array();
$conditions[2] = "3";
$conditions[3] = "A";
$fh = fopen('textfile.txt', 'r'); // open input file
$line= fgets($fh); // get a line from the file
$second = (preg_split("/[\s]+/", $line))[1]; // get 2nd column in a split by whitespace
fclose($fh); // close file
$search = "3 A";
$matches = array();
$fp = fopen("file.txt", "r");
while (!feof($fp)) {
  $line = fgets($fp, 4096);
  if (strpos($line, $search) !== false) {
    $matches[] = $line;
  }
}
print_r($matches); // voila
// how long is each field?
$field_legths = array(20, 11, 22, 3);

$conditions = array();
$conditions[2] = "3 A"; // search "3 A" in 3rd field (index 2)

$matches = array();
$fp = fopen("file.txt", "r");
while (!feof($fp)) {
  $line = fgets($fp, 4096);

  // split line into row array
  $cursor_pos = 0;
  $row = array();
  foreach ($field_legths as $length) {
    $row[] = trim(substr($line, $curser_pos, $length));
    $cursor_pos += $length;
  }

  // search row array for conditions
  foreach ($conditions as $index => $search) {
     if ($row[$index] == $search) {
       $matches[] = $row;
       break;
     }
  }
}
print_r($matches); // voila
// how long is each field?
$field_legths = array(20, 11, 2, 20, 3);

$conditions = array();
$conditions[2] = "3";
$conditions[3] = "A";