preg_match_all没有给出期望的结果

时间:2012-07-04 07:00:05

标签: php preg-match-all

我有像这样的HTML内容

some html text [link id="1"]  some html text 
some html text [link id="2"]  some html text 
some html text [link id="3" stat="y"]  some html text 
some html text [link id="4" stat="y"]  some html text 

我正在使用

var_dump(preg_match_all('/\[link([^\[]+)\]/',$html_tags, $result));

从中提取[link]代码,它正在给我array这样的

array(2) {
  [0]=> array(4) {
    [0]=> string(13) "[link id="1"]"
    [1]=> string(13) "[link id="2"]"
    [2]=> string(21) "[link id="3" stat="y"]"
    [3]=> string(21) "[link id="4" stat="y"]"
  }
  [1]=> array(4) {
    [0]=> string(7) " id="1""
    [1]=> string(7) " id="2""
    [2]=> string(15) " id="3" stat="y""
    [3]=> string(15) " id="4" stat="y""
  }
}

任何人都可以告诉我如何才能得到这样的结果

array (1){
    [0]=> array (4) {
        [0] => array (2){
            [id]  => string(1) "1"
            [stat] => string(0) ""
        }
        [1] => array (2){
            [id]  => string(1) "2"
            [stat] => string(0) ""
        }
        [2] => array (2){
            [id]  => string(1) "3"
            [stat] => string(1) "y"
        }   
        [3] => array (2){
            [id]  => string(1) "4"
            [stat] => string(1) "y"
        }   
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用自定义编写的函数和array_map。

http://php.net/manual/en/function.array-map.php

//first flatten array
$array = $array[1];
array_map("passone", $array);
array_map("passtwo", $array);


function passone ($n) {
    return substr($n, 1);
}

function passtwo ($n) {
    $nx = explode(" ", $n);
    preg_match("link=\"(.*?)\"", $nx[0], $matches);
    $ret['id'] = $matches[0];
    if (!empty($nx[1]))
    {
        $times = preg_match("stat=\"(.*?)\"", $nx[1], $matches);
        if ($times != 0)
        {
        $ret['stat'] = $matches[0];
        }
    }
    return $ret;
}

这应该适合你。