在我看来,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()
重要编辑
isStart
和isEnd
函数中的正则表达式字符串输入不正确。在行尾之前有一些不可见的符号。正确的正则表达式模式为:'/^Start.*$/'
和'/^End.*$/'
答案 0 :(得分:1)
这一位:
if (isContent($line)){
$entry = new Entry();
$entry->SetReason(extractReason($line));
$entry->SetS_id(extractS_id($line));
$entrys[] = $entry;
}
将始终创建一个新的Entry
并将其添加到您的数组中,但它可以检测到的唯一字段是Reason: ...
和Style: ...
。因此大多数行导致空Entry
s。