2016-02-28 103 views
1

基本上这段代码抓住帖子的第一张图片并将其显示在另一页上。 如果没有图像,它会显示默认图像。使用preg_match检索并显示帖子中的图像

如何修改它使其最多可显示4个图像?根据到preg_match手册中阵列$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"; 
+0

谁能帮助请? – Dave

回答

0

你发现的图像:

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

$matches[1]将具有匹配的第一捕获 括号中的子模式的文本,等等。

所以,你应该遍历从1 $images阵列5,如果$images[$i]没有清空该图像添加到您的拇指。尝试是这样的:

<?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"; 
0

您可能需要使用preg_match_all代替:

$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); 

输出:

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 
     ) 

) 
相关问题