Search code examples
phpshortcodetext-extractiontext-parsingwordpress-shortcode

Get src from square-braced shortcode text


I am adding images to a WP site via a shortcode:

[figure src="" url"" caption=""]

Where the src is the image source, the url is the link to a larger image (if wanted), and the caption is the caption.

I am trying to get the src from the above basing it off this code:

$pattern = '/<img[^>]*src=\"?(?<src>[^\"]*)\"?[^>]*>/im';
preg_match( $pattern, $html, $matches ); 
if($matches['src']) {
    return $matches['src'];
}

But am trying to figure out how to get the [figure] match.


Solution

  • /\[figure(( src="(?<src>[^"]+)")?|( url="(?<url>[^"]+)")?|( caption="(?<caption>[^"]+)")?)*\]/i
    

    [figure url="http://example.com/large.gif" caption="my caption" src="http://example.com/figure.gif"]

    Array
    (
        [0] => [figure url="http://example.com/large.gif" caption="my caption" src="http://example.com/figure.gif"]
        [1] => 
        [2] =>  src="http://example.com/figure.gif"
        [src] => http://example.com/figure.gif
        [3] => http://example.com/figure.gif
        [4] =>  url="http://example.com/large.gif"
        [url] => http://example.com/large.gif
        [5] => http://example.com/large.gif
        [6] =>  caption="my caption"
        [caption] =>  my caption
        [7] => my caption
    )