WordPress pull images and video shortcodes from post using regex

Hoping someone can help me out with this. I’m already pulling images from wordpress posts using a regex. Can’t figure out how to pull both video and images though. Sorry I suck at regex. Here’s the code I’m using:

 <?php
    $PostContent = $post->post_content;
    $SearchPattern = '~<img [^>]* />~';

// Run preg_match_all to grab all the images and save the results in $aPics
    preg_match_all( $SearchPattern, $PostContent, $allPics );

// Check to see if we have at least 1 image
    $iNumberOfPics = count($allPics[0]);

    if ( $iNumberOfPics > 0 ) {
        // Now here you would do whatever you need to do with the images
        // For this example the images are just displayed
        for ( $i=0; $i < $iNumberOfPics ; $i++ ) {
            echo '<li>' . $allPics[0][$i] . '</li>';
        };
    };
?>

Any Idea how to edit the searchpattern to also pull wordpress video embeds from the post content like this:

Read More

Appreciate any advice. – Sean

Related posts

Leave a Reply

1 comment

  1. The first regex is matching a html img element. So you want to match shortcodes which contains video info.

    The following regex matches what I think you want, and captures width, height and m4v attributes in groups 1, 2 and 3

    ~(?<=[video)s+width="([^"]+)"s+height="([^"]+)"s+m4v="([^"]+)"]~
    

    EXPLAINED

    (?<=[video)s+ – Match this string literally plus one or more whitespaces following it

    width=" – Match this string literally

    ([^”]+)”s+ – capture everything that’s not a double quote, then match a double quote plus one or more spaces

    height=" – Match this string literally

    ([^”]+)”s+ – Capture everything that’s not a double quote, then match a double quote plus one or more spaces

    m4v=" – Capture this string literally

    ([^"]+)"] – Capture everything that’s not a double quote, then match a double quote followed by the closing square bracket