在PHP中使用标记解析文本文件

时间:2011-07-13 17:51:24

标签: php parsing text-files

我有一个.txt文件,如下所示:

Title: Test
Author: zad0xsis
Date: July 13th, 2011
Body: This is a test post and this can continue until the file end

如何让PHP识别“标签”并将内容转换为新字符串?提前致谢! :d

6 个答案:

答案 0 :(得分:5)

$fc = file('some_file.txt'); // read file into array
foreach ($fc as $line) {
    list($tag, $content) = explode(':', $line, 2);
    // do something here
}

现在,每个文件中有多个不相关的集合吗?如果是这样,你将不得不寻找一些标记,也许是一个新行,并进行重置。希望你能自己解决这个问题。

您可以查看一些功能:

编辑:略微扩展示例:

$fc = file('some_file.txt'); // read file into array
foreach ($fc as $index => $line) {
    list($tag, $content) = explode(':', $line, 2);
    // do something here
    if ('body' == strtolower($tag)) {
        $content = join(array_slice($fc, $index + 1, count($fc)));
        break;
    }
}

为您提供更多功能!

答案 1 :(得分:3)

另一种解决方案:demo here

<?php

  //$sample = file_get_contents('myfile.txt'); // read from file

  $sample = "Title: Test
Author: zad0xsis
Date: July 13th, 2011
Body: This is a test post and this can continue until the file end";

  $re = '/^(?<tag>\w+):\s?(?<content>.*)$/m';

  $matches = null;
  if (preg_match_all($re, $sample, $matches))
  {
    for ($_ = 0; $_ < count($matches['tag']); $_++)
      printf("TAG: %s\r\nCONTENT: %s\r\n\r\n", $matches['tag'][$_], $matches['content'][$_]);
  }

产生

TAG: Title
CONTENT: Test

TAG: Author
CONTENT: zad0xsis

TAG: Date
CONTENT: July 13th, 2011

TAG: Body
CONTENT: This is a test post and this can continue until the file end

以为我只为GP使用命名标签。 此外,如果需要,您可以将(?<tag>\w+)替换为更加模糊的内容,例如(?<tag>.*?),如果可能有空格,数字等

答案 2 :(得分:2)

<?php
$tagValue = array();
$file = fopen("welcome.txt", "r") or exit("Unable to open file!");

while(!feof($file))
{
  $line = fgets($file);
  $tagDelimiter = strpos ($line ,":");
  $tag = substr($line,0,$tagDelimiter);
  $value = substr($line,$tagDelimiter+1,strlen($line)-$tagDelimiter);
  $tagValue[$tag] = $value;
}
fclose($file);
?>

您可以访问您的数据:$tagValue["Title"]

答案 3 :(得分:2)

$file = file("file.txt");
foreach($file as $line)
{
    preg_match("|(.*?): (.*?)|", $line, $match);
    $tag = $match[1];
    $content = $match[2];
}

答案 4 :(得分:1)

你可以这样做:

$file = file('file.txt');

foreach($file as $line)
{
    if(preg_match('/(.*) : (.*)/iUs', $line, $match)
    {
         $tag = $match[1];
         $value = $match[2]
    }
}

答案 5 :(得分:0)

使用strpos()substr()

function parse($filename)
{
  $lines = file($filename);
  $content = array();
  foreach ($lines as $line)
  {
    $posColon = strpos($line, ":");
    $tag = substr($line, 0, $posColon);
    $body = substr($line, $posColon+1);

    $content[$tag] = trim($body);
  }
  return $content;
}