php - 如何通过php过滤任意给定数量的html标签

标签 php html image dom random

我正在做一个项目,我想在其中随机显示任何给定数量的结果假设,我有六个 <html>图片标签,我只想随机显示三个,这样每次刷新页面时,它都会随机显示任意六个图片中的任意三个

我正在使用 html 代码作为示例

<html>
  <body>
    <div class=1>
      <a href="http://example1.com">
        <div>
          <img src="image1.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example2.com">
        <div>
          <img src="image2.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example3.com">
        <div>
          <img src="image3.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example4.com">
        <div>
          <img src="image4.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example5.com">
        <div>
          <img src="image5.jpg">
        </div>
      </a>
    </div>
    <div class=1>
      <a href="http://example6.com">
        <div>
          <img src="image6.jpg">
        </div>
      </a>
    </div>
  </body>
</html>

在这六张图片中,我只想每次通过 php 显示任意三张图片。这可能吗?我该怎么做? 希望您能找到更好的解决方案。 我还想显示其他标签,如图像中的链接和更多标签,以便我可以通过 css 以更好的方式显示图像,所以我认为可以通过 switch 语句更轻松地完成

最佳答案

假设您有一个包含所有图像的数组。从该列表中,我们随机获得 3 张图像的 key 。然后我们通过循环回显 img 标签:

<html>
<body>
<?php
$images = [
    'image1.jpg',
    'image2.jpg',
    'image3.jpg',
    'image4.jpg',
    'image5.jpg',
    'image6.jpg'
];

// Selects 3 random array values and returns the key for each value
$randomkeys = array_rand($images, 3);

// Here we loop through the given index keys from the $images array.
// For each key we will then get the value from $images with the index $key
foreach ($randomkeys as $key) {
    // I end with PHP_EOL (End of line) so the source code will look a bit prettier.
    echo "<div class=\"image\"><a href=\"{$images[$key]}\"><img src=\"{$images[$key]}\"></a></div>".PHP_EOL;
}
?>
</body>
</html>

如果有什么不明白的,请告诉我

编辑 1:添加更多标签
向输出添加更多标签并不难。如果您知道如何回显字符串和变量,您应该能够轻松添加更多标签或按照您想要的方式更改它们。

正如您在更新中看到的那样,我已将类 image 添加到 ,并将链接指向与图像相同的路径,因此当您单击它时,它只会在同一个窗口。

关于php - 如何通过php过滤任意给定数量的html标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32211827/

相关文章:

当 MySQL 查询花费超过 X 秒时,PHP PDO 执行以中止?

php - 检索 PHP --with-config-file-scan-dir 开关的值

php - 从 Ajax 调用时文件下载脚本不起作用

php - 在 PHP/MySQL DB 中存储和检索数组的最佳方法是什么

java - 如何通过makePostRequest()中的ajax调用发送文件并通过 Controller 中的请求参数获取它

html - 使用 CSS 将 Img Src 更改为父级 A href

html - 如何使用CSS将标题居中?

android - 加载远程图像

php - 如何使图像的背景透明度为0?

image - Hessian 矩阵的特征向量和特征值