帮助regexp

时间:2011-09-06 09:48:51

标签: php regex

我有这样的标签

[tag id="4554" align="center"]

如何将标记作为数组中的键,然后所有参数都是动态的,并作为key =>插入数组中价值如

Array (
    [tag] => Array
        (
            [id] => 4554
            [align] => "center"
        )

)

2 个答案:

答案 0 :(得分:2)

$string = '[tag id="4554" align="center"]';

preg_match_all('/\[tag id="(?P<id>[^"]+)" align="(?P<align>[^"]+)"\]/', $string, $matches, PREG_SET_ORDER);

foreach($matches as $match) {
    $tag = array(
        'tag' => array(
            'id' => $match['id'],
            'align' => $match['align'],
        ),
    );  
    print_r($tag);
}

在此处试试:http://ideone.com/72AxJ

答案 1 :(得分:1)

我通常喜欢使用正则表达式的算法:

$str = '[tag id="4554" align="center"]';

$arr = explode(" ",trim($str,'[]'));

$mainkey = array_shift($arr);

$temp = array();
foreach($arr as $part)
{
    $parts = explode("=",$part);
    $temp[$parts[0]] = trim($parts[1], '"');
}

$arr2[$mainkey] = $temp;

print_r($arr2);

输出:

Array
(
    [tag] => Array
        (
            [id] => 4554
            [align] => center
        )

)