3

这很接近,但无法匹配连续的“属性”:

$string = "single attribute [include file=\"bob.txt\"] multiple attributes [another prop=\"val\" attr=\"one\"] no attributes [tag] etc";
preg_match_all('/\[((\w+)((\s(\w+)="([^"]+)"))*)\]/', $string, $matches, PREG_SET_ORDER);
print '<pre>' . print_r($matches, TRUE) . '</pre>';

回馈以下内容:

Array
(
    [0] => Array
        (
            [0] => [include file="bob.txt"]
            [1] => include file="bob.txt"
            [2] => include
            [3] =>  file="bob.txt"
            [4] =>  file="bob.txt"
            [5] => file
            [6] => bob.txt
        )

    [1] => Array
        (
            [0] => [another prop="val" attr="one"]
            [1] => another prop="val" attr="one"
            [2] => another
            [3] =>  attr="one"
            [4] =>  attr="one"
            [5] => attr
            [6] => one
        )

    [2] => Array
        (
            [0] => [tag]
            [1] => tag
            [2] => tag
        )

)

其中[2]是标签名,[5]是属性名,[6]是属性值。

故障发生在第二个节点上 - 它捕获attr="one"但没有prop="val"

蒂亚。

(这仅用于有限的、受控的使用——不是广泛分布——所以我不需要担心单引号或转义的双引号)

4

1 回答 1

1

不幸的是,没有办法重复这样的捕获组。就个人而言,我会使用preg_match匹配标签本身(即删除正则表达式中的所有额外括号),然后 foreach 匹配您可以提取属性。像这样的东西:

$string = "single attribute [include file=\"bob.txt\"] multiple attributes [another prop=\"val\" attr=\"one\"] no attributes [tag] etc";
preg_match_all('/\[\w+(?:\s\w+="[^"]+")*\]/', $string, $matches);
foreach($matches[0] as $m) {
    preg_match('/^\w+/', $m, $tagname); $tagname = $tagname[0];
    preg_match_all('/\s(\w+)="([^"]+)"/', $m, $attrs, PREG_SET_ORDER);
    // do something with $tagname and $attrs
}

请注意,如果您打算用一些内容替换标签,您应该preg_replace_callback像这样使用:

$string = "single attribute [include file=\"bob.txt\"] multiple attributes [another prop=\"val\" attr=\"one\"] no attributes [tag] etc";
$output = preg_replace_callback('/\[\w+(?:\s\w+="[^"]+")*\]/', $string, function($match) {
    preg_match('/^\w+/', $m, $tagname); $tagname = $tagname[0];
    preg_match_all('/\s(\w+)="([^"]+)"/', $m, $attrs, PREG_SET_ORDER);
    $result = // do something with $tagname and $attrs
    return $result;
});
于 2013-03-19T04:49:21.607 回答