Matching wordpress shortcodes inside a given string

I wanted to match shortcodes inside a string and found the following regex from here. It works fine. But i want to learn how it works.

Can anyone plz explain me the components of this regex and how it matches the shortcode.

preg_match_all('%(?<=[shortcode]).*?(?=[/shortcode])%s',$content, $result, PREG_PATTERN_ORDER);

Related posts

Leave a Reply

1 comment

  1. There are tools to explain regular expressions.

    Yours for example:

    NODE                     EXPLANATION
    ----------------------------------------------------------------------
      (?<=                     look behind to see if there is:
    ----------------------------------------------------------------------
        [                       '['
    ----------------------------------------------------------------------
        shortcode                'shortcode'
    ----------------------------------------------------------------------
        ]                       ']'
    ----------------------------------------------------------------------
      )                        end of look-behind
    ----------------------------------------------------------------------
      .*?                      any character  (0 or more times
                               (matching the least amount possible)
    ----------------------------------------------------------------------
      (?=                      look ahead to see if there is:
    ----------------------------------------------------------------------
        [                       '['
    ----------------------------------------------------------------------
        /shortcode               '/shortcode'
    ----------------------------------------------------------------------
        ]                       ']'
    ----------------------------------------------------------------------
      )                        end of look-ahead
    ----------------------------------------------------------------------
    

    Read more about the assertions on http://www.regular-expressions.info/lookaround.html