preg_match 替换错了

preg_match is replacing wrong

我正在尝试编写一个小型解析器,但它没有按预期工作:

<<IF [10] == [10] FI>>hello<<IF [30] < [10] FI>> # input
<>hello<>                                        # current output
1hello0                                          # intended output

我想我做错了preg_match

<?php

ini_set('display_errors',1);
ini_set('display_startup_errors',1);
error_reporting(-1);

echo parse('<<IF [10] == [10] FI>>hello<<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;
}

?>

有这一行

if(preg_match_all("/if+(.*?)fi/", $match, $ifs)) {  

它检查确切的 'if' 字符串。解析后的字符串有'IF'。这不是一场比赛。它需要

if(preg_match_all("/if+(.*?)fi/i", $match, $ifs)) {  

最后一个正则表达式模式定界符后的 'i' 使匹配不区分大小写。
所以现在它匹配大写或小写字母。