问题 如何通过php过滤任何给定数量的html标签


我正在开展一个项目,我希望随机显示任意给定数量的结果,我有六个 <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语句更容易完成


3817
2017-08-25 18:51


起源

将文件名放在一个数组中。 array_rand() 接着 foreach。要么 shuffle() 然后循环3次。 - AbraCadaver
假设我必须向每个图像展示一些其他东西,你能告诉我如何做到这一点 - learner
什么 其他事情? - AbraCadaver
其他标签,如图像中的链接等等 <div> 标签,以便我可以通过CSS更好地显示图像 - learner
如果你想要一个可以获得定义数量的随机图像的PHP代码及其从现有页面到另一个页面的链接,@ learner可以查看我的答案。我认为这就是你想要做的事情并希望它有所帮助。请享用 :) - aimme


答案:


刚扩大 莫滕的代码:

<html>
<body>
<?php
$images = array(
    array('img' => 'image1.jpg', 'url' => 'http://example1.com', 'div' => 'class="d1"'),
    array('img' => 'image2.jpg', 'url' => 'http://example2.com', 'div' => 'class="d2"'),
    array('img' => 'image3.jpg', 'url' => 'http://example3.com', 'div' => 'class="d3"'),
    array('img' => 'image4.jpg', 'url' => 'http://example4.com', 'div' => 'class="d4"'),
    array('img' => 'image5.jpg', 'url' => 'http://example5.com', 'div' => 'class="d5"'),
    array('img' => 'image6.jpg', 'url' => 'http://example6.com', 'div' => 'class="d6"')
);

// 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="1">' . PHP_EOL . '<a href="' . $images[$key]['url'] . '">' . PHP_EOL . '<div ' . $images[$key]['div'] . '>' . PHP_EOL . '<img src="' . $images[$key]['img'] . '">' . PHP_EOL . '</div>' . PHP_EOL . '</a></div>' . PHP_EOL;
}
?>
</body>
</html>

结果: https://3v4l.org/OAc6l


2
2017-08-28 23:25



为什么你使用'<div class = \“image \”>'。而不是这个。 '<div class =“image”>' - learner
因为他刚刚扩展了我的答案,@ learner。我选择那种风格的原因是我可以使用的 {$images['key']}直接而不是通过写入连接字符串 echo 'something ' . $images['key'] . ' something'; - Morten
@learner为imgs添加了div,更改为长语法,更改了结果URL - Nicholas Vasilaki
@learner我在7小时前和2天前在网上看到你了,但你对这个问题并不积极。你还在等待赏金到期吗? - Nicholas Vasilaki


假设你有一个包含所有图像的数组。从该列表中,我们随机获取3个图像的键。然后我们通过一个循环回显出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 到,并使链接指向与图像相同的路径,因此当您单击它时,它将只在同一窗口中打开图像。


5
2017-08-25 19:03



您也可以使用array_rand()返回的值,而不是不必要地索引到数组中。 - pestilence669
带有回声的“逗号”而不是“句号”会更快。句点创建一个新的字符串值,逗号只是将值附加到结尾。 - pestilence669
array_rand() 仅返回给定数组中的键。您没有从数组中获取值。因此,您必须对数组@ pestilence669进行索引 - Morten
是。我的错。我甚至都不高。 - pestilence669
我编辑了这个问题,我也希望在图像中显示一些其他标签,例如链接 <div> 标签,以便我可以通过CSS更好地显示图像 - learner


<?php
  $images=array('image1.jpg','image2.jpg','image3.jpg','image4.jpg','image5.jpg','image6.jpg');
shuffle($images);
for($i=0;$i<=2;$i++){
 echo '<img src="'.$images[$i].'" />';
 }
?>

3
2017-08-25 19:03



完美地表现六种图像约束。几十次之后真的变得浪费了。 - pestilence669
这个答案是完美的,但它回答了OP问题的一半,请尝试也包括链接(<a></a>) - Luthando Ntsekwa


就像@AbraCadaver说的那样。

<?php
// vim: set ts=4 sw=4 et:

$myImages = array_map(function($i) { return "/foo$i.jpg"; }, range(1, 6));

foreach (array_map('htmlspecialchars', array_map(function ($i) { global $myImages; return $myImages[$i]; }, array_rand($myImages, 3))) as $image)
    echo "<img src=\"$image\"/>\n";

0
2017-08-25 19:05





You can keep your src paths in an array. Then you can use array_rand() function to get random array index. 

For example:
<?php

$allImages = ["images1.jpg","images2.jpg","images3.jpg","images4.jpg","images5.jpg","images6.jpg"];

//this will return random keys of $allImages array
$randomKeys = array_rand($allImages, 3);

foreach($randomKeys as $key){ ?>
  <div><a href="#"><img src="<?php echo $allImages[$key] ?> " ></a></div>
<?php
}
?>

这是你如何使用PHP来做到这一点


0
2017-08-25 19:03



我编辑了这个问题,我也希望在图像中显示一些其他标签,例如链接 <div> 标签,以便我可以通过CSS更好地显示图像 - learner
那么你可以添加任何东西,但是你想在每个循环的php中添加。 - Imran
你可以为我给出的例子更新你的答案吗? - learner
我编辑了我的答案。不,你可以做任何你想做的事 div, a 要么 img 标签. In the src`我刚刚添加了php变量来显示随机选择的图像路径。我这解决了你的问题。请批准这个答案。祝你好运。 - Imran
我使用不同的网址与所有图像 - learner


在这种情况下,你的意思是如果页面已经准备好(可能是页面是外部网页,或者其他已经设计的页面)我会使用 简单的Html Dom下载 并将该文件夹包含在项目中。

example.html的

<html>
<style>
img{
    width:100px;
    height:100px;
}
</style>
 <body>
<div class=1>
<a href="http://example1.com">
<div>                               
<img src="image (1).jpg" >                                     
</div>
</a></div>
<div class=1>
<a href="http://example2.com">
<div>                               
<img src="image (2).jpg" >                                     
</div>
</a></div>      <div class=1>
<a href="http://example3.com">
<div>                               
<img src="image (3).jpg" >                                     
</div>
</a></div>
<div class=1>
<a href="http://example4.com">
<div>                               
<img src="image (4).jpg" >                                     
</div>
</a></div>
<div class=1>
<a href="http://example5.com">
<div>                               
<img src="image (5).jpg" >                                     
</div>
</a></div>
<div class=1>
<a href="http://example6.com">
<div>                               
<img src="image (6).jpg" >                                     
</div>
</a></div>
 </body>
 </html>

myphp.php

/**echo '<style>
img{
    width:100px;
    height:100px;
}
</style>';**/

//using Simple HTML DOM. This file is in Simple Html Dom folder downloaded
include('simple_html_dom.php');
// get DOM from URL or file
$html = file_get_html('example.html');// you can write your external website file here www.external.com/index.html

// find all link
foreach($html->find('a') as $e) 
    //echo $e->href . '<br>';
    $image_with_link['link'][]=$e->href;
// find all image
foreach($html->find('img') as $e)
    //echo $e->src . '<br>';
    $image_with_link['image'][]=$e->src;

//for debugging
//echo '<pre>';
//print_r($image_with_link);
//echo '</pre>';

//loop number of times, here i want to display three images
for($i=0;$i<3;$i++){
//get random key from array
$rand=array_rand($image_with_link['image'],1);

//print 3 images with its links
echo '<a href="'.$image_with_link['link'][$i].'" />';
echo '<img src="'.$image_with_link['image'][$i].'" />';
}

0
2017-08-31 14:51





将代码视为一个大字符串。去掉 <HTML></HTML><BODY>,和 </BODY> 从那个字符串。您可以随时添加它们。接下来,爆炸字符串 "<DIV "。对于创建的数组,请添加 "<DIV " 到每个元素的开头。您现在有一个包含每个div部分的数组,其中包含您想要的每个图像和链接。然后,您可以从该数组中随机选择一个并根据需要插入:

// remove HTML and BODY tags
    $remove1 = str_replace("<HTML>", "", $original);
    $remove2 = str_replace("<BODY>", "", $remove1);
    $remove3 = str_replace("</HTML>", "", $remove2);
    $cleaned = str_replace("</BODY>", "", $remove3);

// explode remaining code around "<DIV " so we have each division for each image
    $codeArray = explode("<DIV ", $cleaned);

// with our code sectioned in an array, add "<DIV " back to the start
// of each element in the array
    for ($x = 0; $x < count($codeArray); $x++){
        $codeArray[$x] =. "<DIV ";
    }

// the $codeArray now has $x elements of the sections that contain the 
// links and images you want.
// You can now randomly grab the div's that you want, by
// Shuffling that array, pick the first X images you want, and then
// echo back out the code you want.
    shuffle($codeArray);
    echo "<HTML>";
    echo "<BODY>";
    for ($x = 0; $x < $whateverNumberOfImagesYouWant; $x++){
        echo $codeArray[$x];
    }
    echo "</BODY>";
    echo "</HTML>";

0
2017-09-03 13:47