原始字符串为:
$str='[a]
a=1
b=?,/^[0-9]$/
c=3
[b]
time1=2009-11-30 17:30:00
time2=2009-12-01 17:40:00
[c]
d=?,/^[1-5]$/
e=?,/^[0,1]$/
[d]
type=1';
要求用preg_match_all('正则……',$str,$matches)来写,使得匹配结果数据为:
$matches[0][0]='[a]
a=1
b=?,/^[0-9]$/
c=3'
$matches[0][1]='[b]
time1=2009-11-30 17:30:00
time2=2009-12-01 17:40:00'
$matches[0][2]='[c]
d=?,/^[1-5]$/
e=?,/^[0,1]$/' 
……
以此类推,请问preg_match_all里的正则要怎么写,谢谢了!

解决方案 »

  1.   

    对了,忘说了,每一行里的[] 里的字符并不是a、b、c、d这样有规则的排序,可能是一个字符串什么的
      

  2.   

    用 preg_split 就简单多了
    $str = '[a] 
    a=1 
    b=?,/^[0-9]$/ 
    c=3 
    [b] 
    time1=2009-11-30 17:30:00 
    time2=2009-12-01 17:40:00 
    [c] 
    d=?,/^[1-5]$/ 
    e=?,/^[0,1]$/ 
    [d] 
    type=1';$p = '/^\[\w+\].+/ms';
    $r = preg_split('/(\[\w+\])/', $str, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
    print_r($r);
      

  3.   

    如果是ini文件,那么应按规则写
    [a] 
    a=1 
    b="?,/^[0-9]$/"
    c=3 
    [b] 
    time1=2009-11-30 17:30:00 
    time2=2009-12-01 17:40:00 
    [c] 
    d="?,/^[1-5]$/"
    e="?,/^[0,1]$/"
    [d] 
    type=1然后 $ar = parse_ini_file('test.ini'); 即可
      

  4.   

    还可以
    $ar = parse_ini_file('test.ini', true);
    print_r($ar);Array
    (
        [a] => Array
            (
                [a] => 1
                [b] => ?,/^[0-9]$/
                [c] => 3
            )    [b] => Array
            (
                [time1] => 2009-11-30 17:30:00
                [time2] => 2009-12-01 17:40:00
            )    [c] => Array
            (
                [d] => ?,/^[1-5]$/
                [e] => ?,/^[0,1]$/
            )    [d] => Array
            (
                [type] => 1
            ))
     
      

  5.   

    感谢楼上的解答。现在还有点问题,首先这还不是ini文件,还是字符串,处理里面的数据后才存为ini文件,所以不能用parse_ini_file('test.ini', true)这种方式。
    然后试了你的
    $r = preg_split('/(\[\w+\])/', $str, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
    写法,但是还是有点问题,当里面的
    [c] 
    d=?,/^[1-5]$/ 
    e=?,/^[0,1]$/ 
    数据变成比如:
    [c] 
    d=?,/^[1-5]$/ 
    e=?,/^[abcd]$/
    后就不是我想要的结果了。