0

我有一个像这样的 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"
        }   
    }
}
4

1 回答 1

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;
}

这应该适合你。

于 2012-07-04T07:21:43.837 回答