使用preg_match从帖子中检索和显示图像

Basically this piece of code grab the first image of the post and display it at another page. If no images, it will show the default image.

How do I modify it to make it display max up to 4 images ?

<?php

$Imagesrc = C('Plugin.IndexPostImage.Image','/images/default.png');

preg_match(
    '#\<img.+?src="([^"]*).+?\>#s', 
    $Sender->EventArguments['Post']->Body, 
    $images
);

if ($images[1]) {
    $Imagesrc = $images[1];
}

$thumbs ='<a class="IndexImg" href="'. 
    $Sender->EventArguments['Post']->Url .'">'. 
    Img($Imagesrc, array('title'=>$sline,'class'=>"IndexImg")).'</a>';

echo "$thumbs";

Your found images in array $images according to to preg_match manual:

int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]] )

$matches[1] will have the text that matched the first captured parenthesized subpattern, and so on.

So you should iterate over $images array from 1 to 5 and if $images[$i] not empty add this image to your thumbs. Try something like this:

<?php

$Imagesrc = C('Plugin.IndexPostImage.Image','/images/default.png');

preg_match(
    '#\<img.+?src="([^"]*).+?\>#s',
    $Sender->EventArguments['Post']->Body,
    $images
);

$thumbs = "";
for ($i = 1; $i <= 5; $i) {
    if(!empty($images[$i])) {
        $thumbs .= '<a class="IndexImg" href="' .
            $Sender->EventArguments['Post']->Url . '">' .
            Img($images[$i], array('title' => $sline, 'class' => "IndexImg")) . '</a>';
    } else {
        break;
    }
}

echo "$thumbs";

You may want to use preg_match_all instead:

$string = 'blah blah <img src="img1.png">blah blah <img src="img2.png">blah blah <img src="img3.png">';
preg_match_all(
    '#<img.+?src="([^"]*)#s',
    $string,
    $images
);
print_r($images);

Output:

Array
(
    [0] => Array
        (
            [0] => <img src="img1.png
            [1] => <img src="img2.png
            [2] => <img src="img3.png
        )

    [1] => Array
        (
            [0] => img1.png
            [1] => img2.png
            [2] => img3.png
        )

)