phpregexshortcodetext-extraction

Parse a curly braced shortcode and return the value of a specified attribute


I'm converting some shortcode information from an old CMS I'm using. In some article body text, I need to get the ID from some pre-existing callouts

{image id="27411" shape="landscape" align="right"}

There can be multiple callouts like this within one body of text. Is there a way to have this information returned as an array of IDs? The only important information is the ID, the rest is irrelevant.


Solution

  • If it's always in that format, use preg_match_all(), like this:

    preg_match_all( '#\{image id="(\d+)"[^\}]+\}#', $input, $matches);
    

    Your array of IDs will be in $matches[1].

    So, for your example input, this outputs:

    array(1) {
      [0]=>
      string(5) "27411"
    }