【问题标题】:Retrieving & displaying images from a post with preg_match使用 preg_match 从帖子中检索和显示图像
【发布时间】:2016-02-28 01:39:39
【问题描述】:

基本上,这段代码会抓取帖子的第一张图片并将其显示在另一个页面上。 如果没有图像,它将显示默认图像。

如何修改它以使其最多显示 4 张图像?

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

【问题讨论】:

    标签: php regex preg-match


    【解决方案1】:

    您根据preg_match 手册在数组$images 中找到的图像:

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

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

    因此,您应该从 1 到 5 遍历 $images 数组,如果 $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";
    

    【讨论】:

      【解决方案2】:

      您可能想改用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
              )
      
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-24
        • 2017-09-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多