Php Regexp问题,多个匹配,但为什么?
我有以下案文: 满足于Php Regexp问题,多个匹配,但为什么?,php,regex,preg-match,Php,Regex,Preg Match,我有以下案文: 满足于 [row marginTop="10" marginBottom="10"] [column_3] [column][article id="12" /][/column] [column][article id="13" /][/column] [column][article id="14" /][/column] [/column_3] [/row] 当我这样做的时候: $pattern = '/^(\[([a-zA-Z0-9][a-zA-Z0-9_]
[row marginTop="10" marginBottom="10"]
[column_3]
[column][article id="12" /][/column]
[column][article id="13" /][/column]
[column][article id="14" /][/column]
[/column_3]
[/row]
当我这样做的时候:
$pattern = '/^(\[([a-zA-Z0-9][a-zA-Z0-9_]+[a-zA-Z0-9]) *( [a-zA-Z]+(="[^".]*")?)*( *\/)?\])$/';
preg_match($pattern, $text, $matches, PREG_OFFSET_CAPTURE);
print_r($matches);
$pattern='/^(\[([a-zA-Z0-9][a-zA-Z0-9\]+[a-zA-Z0-9])*([a-zA-Z]+(=“[^”]*”)*(*\/)?\]$/”;
预匹配($pattern,$text,$matches,预偏移捕获);
打印(匹配项);
结果是:
Array
(
[0] => Array
(
[0] => [row marginTop="10" marginBottom="10"]
[1] => 137
)
[1] => Array
(
[0] => marginBottom="10"
[1] => 156
)
[2] => Array
(
[0] => ="10"
[1] => 166
)
)
排列
(
[0]=>阵列
(
[0]=>[row marginTop=“10”marginBottom=“10”]
[1] => 137
)
[1] =>阵列
(
[0]=>marginBottom=“10”
[1] => 156
)
[2] =>阵列
(
[0] => ="10"
[1] => 166
)
)
为什么?我能做些什么来避免这种情况呢?子模式表示法
(…)
有两个目的:分组和捕获。因此,$matches
以所有子模式的内容以及整个匹配结束
如果不需要,可以删除分组时不需要的括号,如果需要分组而不捕获,可以使用非捕获子模式表示法(?:…)
:
(有关更多信息,请参阅。)您的预期输出是什么?数组([0]=>Array([0]=>row marginTop=“10”marginBottom=“10”][1]=>137))就这一个。实际上,我不想在子模式上找到匹配项。只是整个模式。Sry对于我糟糕的英语:\offtopic,但您可能可以将
[a-zA-Z0-9_]
替换为\w
,具体取决于正则表达式引擎、其他范围([…]
)还应更换正则表达式引擎未修复,我将始终保持不同,因此我觉得[a-zA-Z0-9_u]安全且“交叉兼容”。
$pattern = '/^\[[a-zA-Z0-9][a-zA-Z0-9_]+[a-zA-Z0-9] *(?: [a-zA-Z]+(?:="[^".]*")?)*(?: *\/)?\]$/';