0
私の意見では、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()
重要EDIT
isStart
およびisEnd
関数の正規表現文字列の入力が正しくありませんでした。ラインの終わりの前にいくつかの目に見えないシンボルがありました。正しい正規表現パターンは以下のとおりです。'/^Start.*$/'
と'/^End.*$/'
ええ、私は 'Reason:'と 'S_id:'だけが欲しいですが、出力はすべて乱されています。出力は次のようになります。http://pastebin.com/RnaieuyA。あまりにも多くの結果があり、preg_match()パターンは間違っていて、結果は2の配列です。 '$ match [1]'を出力する必要がありますが、 'undefined offset 1'というエラーが発生します。 –
@ Wolfpack'08:私が言ったように、あなたは各行に対して新しい 'Entry'を作成しています。代わりに、ループに入る前に1つの 'Entry'を作成し、空の行を検出するたびに新しい' Entry'を作成する必要があります。 (しかし、 'isContent'にはバグがあります:常に' 1'を返します。他のものが動作する前に修正する必要があります) – ruakh
ruakh、 '$ entry = new Entry ); 'ifブロック'の外側? –