我想解析这种代码:
{articles mode="extrait" nb="3"}
我正在使用这个正则表达式:
@\{(articles)(?:(?:\s|\ )*(?:(\w+)="(\w+)"))*\}@
但它不起作用,当我执行 preg_match_all 时,这是带有 $matches 参数的 print_r 的结果:
Array (
[0] => {articles mode="extraits" nb="3"}
[1] => articles
[2] => nb
[3] => 3
)
我认为最后一个 * 应该可以获取所有属性,而不仅仅是最后一个。
您看到遗漏或不正确的地方了吗?
提前致谢
最佳答案
$instances = array();
@ preg_match_all( '/\{articles([^\}]+)\}/', $string, $articles );
if ( false === empty( $articles[1][0] ))
{
foreach ( $articles[1] as $article )
{
@ preg_match_all( '/\b(\w+)="([^"]+)"/', $article, $arguments );
if ( false === empty( $arguments[0][0] ))
{
$settings = array();
foreach ( $arguments[0] as $index => $argument )
{
$settings[$arguments[1][$index]] = $arguments[2][$index];
}
$instances[] = $settings;
}
unset( $arguments );
}
}
print_r( $instances );
关于php - 带属性的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13975515/