【问题标题】:combining two codes targeting images结合两个针对图像的代码
【发布时间】:2016-08-15 14:37:14
【问题描述】:

我有两个工作代码,它们对我的 word-press 网站中的图像做两件事。但是,当我按原样使用它们时它们不起作用。我似乎无法将它们结合起来并保留两者的功能。

输出我的 word-press 帖子中的所有图像,最后一张用#last-img 包裹

<?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];
    }
?> 

将最后一张图片作为#last-img的背景

<?php
 preg_match_all('/src="([^"]*)"/i', get_the_content(), $images);
?>

<div id="last-img" style="background:url(<?php echo $images[1][count($images[1])-1] )"> ... </div>

我想显示所有的图片,并将最后一张图片作为#last-img的背景

【问题讨论】:

  • 我正在关注您的代码,但我没有看到第二部分成为#last-img 的背景。或者你的代码将它保存在什么字符串下
  • Ic,它完成了第一部分,但我需要最后一张图像成为#last-img 的背景图像,我最好的方式是最后一张图像两次
  • user3550879 你检查答案了吗?

标签: php html wordpress


【解决方案1】:

你可以这样做:-

<?php
    preg_match_all('/(<img [^>]*>)/', get_the_content(), $images);
    preg_match_all('/src="([^"]*)"/i', get_the_content(), $images1);
    $count = count($images[1]);
    $count1 = count($images1[1]);
    foreach($images[1] as $k=> $img){
        if($k == $count-1){
            $format = '<div id="last-img" style="background:url(%s)"> ... </div>'; // Or $format = "<div id='last-img' style='background:url(%s)'> ... </div>";
            $image = $images1[1][$count1-1];
            echo sprintf($format,$image);
        }else{
            echo $img;
        }
    }
?>

或者

<?php
    preg_match_all('/(<img [^>]*>)/', get_the_content(), $images);
    preg_match_all('/src="([^"]*)"/i', get_the_content(), $images1);
    $count = count($images[1]);
    $count1 = count($images1[1]);
    foreach($images[1] as $k=> $img){
            echo $img;
    }
    $format = '<div id="last-img" style="background:url(%s)"> ... </div>'; // Or $format = "<div id='last-img' style='background:url(%s)'> ... </div>";
    $image = $images1[1][$count1-1];
    echo sprintf($format,$image);
?>

【讨论】:

  • 两者的主要区别是什么?
  • 1.第一个遍历第一个 preg_match 数组并打印所有图像,当最后一个出现时,它添加背景图像(跳过最后一个图像(而不是那个背景图像))。 2. 它也会在相同的地方进行迭代,但是这里所有的图像都会打印出来,然后背景会出现(不跳过任何图像,你的第一个匹配数组将有图像或者没有背景)
猜你喜欢
  • 2021-11-14
  • 1970-01-01
  • 1970-01-01
  • 2020-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
相关资源
最近更新 更多