我有以下代码,它将我 wordpress 帖子中的最后一张图片包装在 #last-img
div 中。
html
<?php
preg_match_all('/(<img [^>]*>)/', get_the_content(), $images);
for( $i=0; isset($images[1]) && $i < count($images[1]); $i++ ) {
if ($i == end(array_keys($images[1]))) {
echo sprintf('<div id="last-img">%s</div>', $images[1][$i]);
continue;
}
echo $images[1][$i];
}
?>
CSS
#last-img { ... }
我希望图像成为 #last-img
的背景,而不仅仅是在其中。
最佳答案
我已经改变了你选择使用的模式,
在遍历整个数组的实例中,您可以在下面的代码中检测到 var 中的最后一个数组:
<?php
preg_match_all('/src="([^"]*)"/i', get_the_content(), $images);
echo $images[1][count($images[1])-1];
?>
您可以随意使用“img src”。 GL.
关于php - 通过php把图片变成背景图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38657958/