Wordpress使用regex从帖子中提取图像和视频短代码


Wordpress pull images and video shortcodes from post using regex

希望有人能帮我解决这个问题。我已经在使用正则表达式从wordpress帖子中提取图像了。但我不知道如何提取视频和图像。对不起,我不懂正则表达式。这是我正在使用的代码:

 <?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>';
        };
    };
?>

任何想法如何编辑搜索模式也从帖子内容中提取wordpress视频嵌入如下:

[video width="640" height="360" m4v="http://localhost/~TandySean/LOH/WP38/wp-content/uploads/2013/11/museum3shot_v1_iphone.m4v"]

感谢您的建议。-Sean

第一个正则表达式匹配一个html img元素。所以你想匹配包含视频信息的短代码。

下面的regex与我认为您想要的匹配,并捕获组'1'2'3 中的宽度、高度和m4v属性

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

解释

(?<='[video)'s+-将此字符串与后面的一个或多个空格进行匹配

width="-完全匹配此字符串

([^"]+)"''s+-捕获所有不是双引号的内容,然后匹配双引号加一个或多个空格

height="-完全匹配此字符串

([^"]+)"''s+-捕获所有不是双引号的内容,然后匹配双引号加一个或多个空格

m4v="-捕获此字符串的字面

([^"]+)"]-捕获所有不是双引号的内容,然后匹配一个双引号,后跟右方括号