以递归方式获取所有preg_match_all匹配项?

时间:2015-11-08 21:20:09

标签: php regex

我正在尝试从字符串中解析一些属性。我正在使用下面的函数,它工作正常,但我想解析所有嵌套的匹配,现在它只解析根级别,当目标是解析所有匹配,甚至包含在其他匹配中的匹配:

function get_all_attributes( $tag, $text ){
    preg_match_all( '/\[(\[?)(embed|wp_caption|caption|gallery|playlist|audio|video|acf|page|row|column|loop\-grid|loop\-grid\-item|grid\-filters|page\-title|page\-section|header|header\-column|header\-menu|header\-logo)(?![\w-])([^\]\/]*(?:\/(?!\])[^\]\/]*)*?)(?:(\/)\]|\](?:([^\[]*+(?:\[(?!\/\2\])[^\[]*+)*+)\[\/\2\])?)(\]?)/s', $text, $matches );
    $out = array();

    if( isset( $matches[2] ) )
    {
        foreach( (array) $matches[2] as $key => $value )
        {
            if( $tag === $value ){
                $out[] = array(
                    'name' => $tag,
                    'attributes' => shortcode_parse_atts( $matches[3][$key] ),
                    'content' => trim($matches[5][$key]),
                );
            }
        }
    }

    return $out;
}

以下是要解析的字符串,它包含来自Wordpress的短代码,我试图将其放在数组中以便以后轻松获取属性:

[page key="2298"]
[page-title key="1446986321457"]aaaa[/page-title]
[page-title key="1446986418207"]bbbbb[/page-title]
[row key="1446893994674"]
    [column key="1446893994674_1"]              
        [image key="1446893994674_1_logo"]ccc[/image]
    [/column]
[/row]

是否可以使用递归正则表达式获取同一数组中的父项和子项的所有字符串?

0 个答案:

没有答案