douluolan9101 2011-08-11 22:31
浏览 21
已采纳

php自定义用preg解析一个字符串

My methods parse strings and do stuff with the information contained in the string. a simple example would be

$string=
"
    user:name,password={$_POST['name']}, {$_POST['password']}(md5); 
    names:name=name;
";
$class->$method($string);

The above would do two insert statements. The first will insert in a table named user the users name and the password encypted in md5.
the second would insert a name in the names table. I'm having setting it up so that characters can be escaped. ie if the users name was p;ez. The string would have p\;ez.
My current method is as follows

    #get position of ;
    $offsetSemi=stripos($s, ";");
    #check if its escaped
    if ($s[$offsetSemi-1]!='\\')
    {
        //not escaped
    }

the problem with the above method is that it will only check the first instance of ;. the other solution i tried was exploding the string on ;. however this would not work because it exploded on all instances including ones that were escaped. the other thing i tried was an explode with the regular expression below

/[^\\\];/

the prolem with this is that it exploded on the charecter before ; on all the instances that were not escaped. is there a way i can explode a string on all instances of ; that are not preceded by a backslash?

  • 写回答

3条回答 默认 最新

  • du248227 2011-08-11 22:44
    关注

    Instead of exploding you can parse the string:

    $arr = array();
    $tmp = "";
    
    for ($i = 0; $i < strlen($s); $i++) {
       switch ($s[$i]) {
          case "\\":
             if ($i < strlen($s) - 1) $tmp .= $s[$i++] . $s[$i++];
          break;
          case ";":
             $arr[] = $tmp;
             $tmp = "";
          break;
          default:
             $tmp .= $s[$i];
       }
    }
    
    if (strlen(trim($tmp)) > 0) { // last section
        $arr[] = $tmp;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路