解析程序:我是如何错误地加载我的对象的


Parsing program: How am I loading my object incorrectly?

在我看来,if (isStart($line)){}if (isEnd($line))块把事情放错了范围。问题区域围绕"/***PROBLEM AREA */"进行评论。

这是我的解析程序:

<?php
  //**CLASS AND OBJECT */
  class Entry
  {
    private $reason;
    private $s_id;
    public function __construct()
    {
      $this->reason     = '';
      $this->s_id       = '';
    }
      //** GETTERS AND SETTERS */
    public function SetReason($reason)
    {
      $this->reason = $reason;
    }
    public function GetReason()
    {
      return $this->reason;
    }
    public function SetS_id($s_id)
    {
      $this->s_id = $s_id;
    }
    public function GetS_id()
    {
      return $this->s_id;
    }
  }
  //** EXTRACTION FUNCTION(S)
  function extractReason($line)
  {
    $matches;
    preg_match('/^Reason:'s+(.*)'s+$/', $line, $matches);
    return $matches[1];
  }  
  function extractS_id($line)
  {
    $matches;
    preg_match('/^S_id:'s+(.*)'s+$/', $line, $matches);
    return $matches[1];
  }
  //** LINE CONTAINST DESIRED EXTRACTION CHECK */
  function isStart($line)
  {
    return preg_match('/^Start$/', $line);
  }
  function isReason($line)
  {
    return preg_match('/^Reason:'s+(.*)$/', $line);
  }
  function isS_id($line)
  {
    return preg_match('/^S_id:'s+(.*)$/', $line);
  }
  function isContent($line)
  {
    return preg_match('/.*$/', $line);
  }
  function isEnd($line)
  {
    return preg_match('/^End$/', $line);
  }


  //** DEFINITION */
  $fName = 'obfile_extractsample.txt';
  $fh    = fopen($fName, 'r');
  $line;
  $entry;
  $entrys = array();
  //** PARSE OPERATION
  if ($fh === FALSE)
    die ('Failed to open file.');
  //**START PROBLEM AREA */
  while (($line = fGets($fh)) !== FALSE)
  {
    if (isStart($line)){
      $entry = new Entry();
      if (isReason($line)){
        $entry->SetReason(extractReason($line));
      }
      if (isS_id($line)){
        $entry->SetS_id(extractS_id($line));
      }
      if (isEnd($line)){
        $entrys[] = $entry;
      }
    }
  }
  //***END PROBLEM AREA */
  echo "<pre>";
    print_r($entrys);
  echo "</pre>";
  fclose($fh);
?>

这是我的示例文件:

Start
Name:      David Foster  
Out Time:  4:36 p.m.    
Back Time: 4:57 p.m.
Reason:    Lunch
S_id:      0611125
End
Start
Name:      Brenda Banks  
Out Time:  5:53 a.m.    
Back Time: 6:30 a.m.
Reason:    Personal
S_id:      0611147
End

这是输出:

Array()

重要编辑

isStartisEnd函数中输入的正则表达式字符串不正确。在这行的末尾之前有一些看不见的符号。正确的正则表达式模式为:'/^Start.*$/''/^End.*$/'

此位:

    if (isContent($line)){
      $entry = new Entry();
      $entry->SetReason(extractReason($line));
      $entry->SetS_id(extractS_id($line));
      $entrys[] = $entry;
    }

将始终创建一个新的Entry并将其添加到阵列中,但它只能检测到Reason: ...Style: ...字段。因此,大多数行导致空的Entrys。