如何在 PHP 数组链接中添加随机数查询字符串


How To Add Random Number Query String Within PHP Array Links

目标是在PHP数组中旋转图像的末尾添加一个随机数,以防止浏览器缓存图像。该数字应附加到图像URL的末尾,我有数组,效果很好。我有一个随机数生成器,它可以工作。在使用 PHP 将随机数应用于数组中的链接时,我做错了。

下面是包含链接和图像的数组示例:

<?php
$content1 = '<a href="http://example.net" title="Example 1" target="_blank"><img src="http://example.com/gallery/image-1.png" alt="Image 1" width="300" height="250" class="gallery-image"></a>';
$content2 = '<a href="http://example.net" title="Example 2" target="_blank"><img src="http://example.com/gallery/image-2.png" alt="Image 2" width="300" height="250" class="gallery-image"></a>';
$content3 = '<a href="http://example.net" title="Example 3" target="_blank"><img src="http://example.com/gallery/image-3.png" alt="Image 3" width="300" height="250" class="gallery-image"></a>';
$content4 = '<a href="http://example.net" title="Example 4" target="_blank"><img src="http://example.com/gallery/image-3.png" alt="Image 4" width="300" height="250" class="gallery-image"></a>';
$content = array($content1, $content2, $content3, $content4,);
shuffle($content);
?>
<?php print $content[0] ?>

这是随机数生成器:

<?php echo rand() . "'n"; ?>

我想要的应该是这样的:

$content1 = '<a href="http://example.net" title="Example 1" target="_blank"><img src="http://example.com/gallery/image-1.png?29384756" alt="Image 1" width="300" height="250" class="gallery-image"></a>';

我试图将随机数生成器放在数组的文本字符串中,但我做错了什么,因为它要么不会生成数字,要么 PHP 代码显示在 HTML 中,所以我不确定随机数如何在数组 HTML 文本中生成。

同样,目标是在图像 URL 的末尾添加一个随机数查询字符串,以便数组仍显示图像并防止浏览器在刷新页面时/如果刷新页面时缓存图像。

有什么想法吗?有什么更好的方法吗?

一个简单的例子:

$rand = rand();
// ...
$content2 = '<a href="http://example.net" title="Example 2" target="_blank"><img src="http://example.com/gallery/image-2.png?' . $rand .'" alt="Image 2" width="300" height="250" class="gallery-image"></a>';
// ...
$content = array($content1, $content2, $content3, $content4,);
shuffle($content);