phparraysregextext-parsingwordpress-shortcode

Parse square-braced shortcode's parameters into a flat array


So I have this regex - regex101:

\[shortcode ([^ ]*)(?:[ ]?([^ ]*)="([^"]*)")*\]

Trying to match on this string

[shortcode contact param1="test 2" param2="test1"]

Right now, the regex matches this:

[contact, param2, test1]

I would like it to match this:

[contact, param1, test 2, param2, test1]

How can I get regex to match the first instance of the parameters pattern, rather than just the last?


Solution

  • You may use

    '~(?:\G(?!^)\s+|\[shortcode\s+(\S+)\s+)([^\s=]+)="([^"]*)"~'
    

    See the regex demo

    Details

    PHP demo

    $re = '~(?:\G(?!^)\s+|\[shortcode\s+(\S+)\s+)([^\s=]+)="([^"]*)"~';
    $str = '[shortcode contact param1="test 2" param2="test1"]';
    $res = [];
    if (preg_match_all($re, $str, $matches, PREG_SET_ORDER, 0)) {
        foreach ($matches as $m) {
            array_shift($m);
            $res = array_merge($res, array_filter($m));
        }
    }
    print_r($res);
    // => Array( [0] => contact [1] => param1  [2] => test 2 [3] => param2  [4] => test1 )