我正在尝试写一个小小的Parser。它只是一个有趣的项目,所以不要指望真的很严重。
问题是,如果我运行我的代码,结果是:
<>Hi World<>
但它应该是:
1Hi world!0
我认为我对“preg_match”做错了。有人能帮助我吗? (我已经用评论标记了preg_match州议员。有人可以帮助我吗?
ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);
echo parse('<<IF [10] == [10] FI>>Hi world!<<IF [30] < [10] FI>>');
function parse($toParse) {
if(preg_match_all("/<<+(.*?)>>/", $toParse, $matches)) {
foreach($matches[1] as $match) {
$save = $match;
$match = str_replace(" ", "", $match);
if(preg_match_all("/if+(.*?)fi/", $match, $ifs)) {
foreach($ifs[1] as $if) {
$if = str_replace(">", "", $if, $gt);
$if = str_replace("<", "", $if, $lt);
$if = str_replace("==", "", $if, $eq);
$if = explode("][", $if);
if(count($if) > 2 || count($if) < 2) die ("Syntax Error!");
for($i=0; $i<count($if); $i++) {
$if[$i] = str_ireplace("[", "", $if[$i]);
$if[$i] = str_ireplace("]", "", $if[$i]);
}
if($gt == 1 && $lt != 1 && $eq != 1) {
if($if[0] > $if[1])
$toParse = preg_replace("/<<".$save.">>/","1", $toParse, 1); // here
else
$toParse = preg_replace($save,"0", $toParse, 1); // here
} else if($gt != 1 && $lt == 1 && $eq != 1) {
if($if[0] < $if[1])
$toParse = preg_replace($save,"1", $toParse, 1); // here
else
$toParse = preg_replace($save,"0", $toParse, 1); // here
} else if($gt != 1 && $lt != 1 && $eq == 1) {
if($if[0] == $if[1])
$toParse = preg_replace($save,"1", $toParse, 1); // here
else
$toParse = preg_replace($save,"0", $toParse, 1); // here
} else {
$toParse = preg_replace($save,"Syntax Error!", $toParse, 1); // here
}
}
}
}
}
return $toParse;
}
?>
答案 0 :(得分:1)
有这一行
if(preg_match_all("/if+(.*?)fi/", $match, $ifs)) {
检查确切的&#39; if&#39;串。解析后的字符串有&#39; IF&#39;。这不是一场比赛。它必须是
if(preg_match_all("/if+(.*?)fi/i", $match, $ifs)) {
&#39; i&#39;,在最后一个正则表达式模式分隔符后,使匹配不区分大小写。
所以现在它匹配大写或小写字母。