这很接近,但无法匹配连续的“属性”:
$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"
蒂亚。
(这仅用于有限的、受控的使用——不是广泛分布——所以我不需要担心单引号或转义的双引号)