Wordpress使用正则表达式从帖子中提取图像和视频短代码

时间:2013-12-15 22:35:03

标签: php regex wordpress

希望有人可以帮我解决这个问题。我已经使用正则表达式从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>';
        };
    };
?>

任何想法如何编辑searchpattern以同时从帖子内容中提取wordpress视频嵌入:

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

欣赏任何建议。 - 肖恩

1 个答案:

答案 0 :(得分:1)

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

以下正则表达式符合我的想法,并在组\1\2\3

中捕获宽度,高度和m4v属性
~(?<=\[video)\s+width="([^"]+)"\s+height="([^"]+)"\s+m4v="([^"]+)"]~

<强> EXPLAINED

(?<=\[video)\s+ - 字面上匹配此字符串以及其后的一个或多个空格

width=" - 按字面意思匹配此字符串

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

height=" - 按字面意思匹配此字符串

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

m4v=" - 按字面意思捕获此字符串

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