【问题标题】:Replace img to background-image div with php用 php 将 img 替换为 background-image div
【发布时间】:2015-10-25 05:09:32
【问题描述】:

有没有办法用下面的 div 标签替换 img 标签?

原始html:

<div class="article">
  <img src="/images/img-1.jpg" alt="alt for image">
</div>

替换的html:

<div class="article">
 <div style="background: transparent url(/images/img-1.jpg) no-repeat;
 background-position: center center; background-size: cover; width: 566px; 
 height: 576px;">alt for image</div>
</div>

(可选)也可以使用父 div 的宽度和高度,即在我的示例中的文章类,而不是定义固定的width: 566px; height: 576px;?

如果可能的话,我想使用str_replace 函数。

str_replace('?????', '?????', $article);

编辑:

article 类可能有多个元素,并且文章类 div 中可能还有其他元素,我需要将 img 更改为 div。

编辑2:

我的意思是我可能在文章 div 中有任何内容,只是想用 div 替换 img。

我可能有:

<div class="article">
  <h1>heading</h1>
  <p>paragraph</p>
  <img src="/images/img-1.jpg" alt="alt for image">
</div>

或者我可能有:

<div class="article">
  <h3>heading</h3>
  <p><img src="/images/img-1.jpg" alt="alt for image"> some paragraph </p>
</div>

所以,我可能在 .article div 中有任何东西,我想从中将 img 替换为 div 之类的

发件人:

<img src="/images/img-1.jpg" alt="alt for image" here-may-be-another-attribute-too>

收件人:

<div style="background: transparent url(/images/img-1.jpg) no-repeat;">alt for image</div>

【问题讨论】:

  • 只需使用width: 100% 和height: 100% 来适应父母的大小。
  • 我需要以像素为单位进行定义。
  • 如果 HTML 是动态创建的,则需要 preg_replace 函数。第二个问题 - 是的。
  • @nevermind 你能用 preg_replace 给我一个答案吗?
  • jquery 如果不是强制使用 php 会更好。

标签: php html css


【解决方案1】:

您可以使用PHP’s native DOM library 来查找和替换html。我写了一些例子,你适应你的情况。希望有所帮助。

更新代码:

$html_str = '<div class="article newclass" id="some_id">
  <h1>heading</h1>
  <p>paragraph</p>
  <img src="images/image.png" alt="alt for image">
  <br>
  <h3>
  <p>paragraph</p>
    <img src="images/image2.png" alt="alt for image3">
  </h3>
  </div>';

$dom = new DOMDocument();
$dom->loadHTML($html_str);
$xpath = new DOMXpath($dom);

foreach ($xpath->query('//div[contains(@class, "article")]//img') as $img) {

  $new_img = replace($img, $width = '566', $height = '576');

  $replacement = $dom->createDocumentFragment();
  $replacement->appendXML($new_img);

  $img->parentNode->replaceChild($replacement, $img);

}

$new_html = $dom->saveXml();
echo $new_html;

function replace($img, $width, $height) {

  $href = $img->getAttribute('src');
  $alt = $img->getAttribute('alt');

  $new_img = '<div style="background: transparent url('.$href.') no-repeat;
    background-position: center center; background-size: cover; width: '.$width.'px;
    height: '.$height.'px;">'.$alt.'</div>';

  return $new_img;
}

替换功能保持不变,仅更改使用 DOM 管理的部分

【讨论】:

  • 在这种情况下,我对 div 中的更多类和文章类中的更多图像的代码稍作改动
  • 是的,我明白,但需要一点时间来更新代码:)
  • 谢谢。我希望你能尽快提供你的答案。我目前正在为你提供最后的赏金。
  • 这在 index.php 中使用时工作正常,但是当我尝试从生成 html 的其他地方时,它向我显示致命错误:调用未定义的函数 replace()。有什么想法吗?
  • 系统找不到replace()函数,需要包含你定义这些函数的文件。
【解决方案2】:

使用 php 类 simplehtmldom (http://simplehtmldom.sourceforge.net/) 您可以使用类似 CSS 的选择器查找和修改 HTML-Dom。

<?php
require_once('simple_html_dom.php');

// Create DOM from string
$html = str_get_html('<div class="article">
  <img src="/images/img-1.jpg" alt="alt for image">
</div>');

$html->find('div.article', 0)->innertext = '<div style="background: transparent url(/images/img-1.jpg) no-repeat;
 background-position: center center; background-size: cover; width: 566px; 
 height: 576px;">alt for image</div>';

/** 
 * Output: <div id="article"><div style="background: transparent url(/images/img-1.jpg) no-repeat;
 * background-position: center center; background-size: cover; width: 566px; 
 * height: 576px;">alt for image</div></div>
 */
echo $html; 
?>

【讨论】:

  • 没有提供我真正想要的答案。所以,我必须使用你的答案。但是我找不到simple_html_dom.php,你能链接一下吗?
【解决方案3】:

给你。一个经过测试和工作的解决方案。如果 PHP 抛出任何错误,就会出现错误报告。子 div 也继承了父 div 的宽度和高度。

<?php

error_reporting(E_ALL);

ini_set("log_errors", 1);

/**
 * Display of all other errors
 */
ini_set("display_errors", 1);

/**
 * Display of all startup errors
 */
ini_set("display_startup_errors", 1);

$content = '
<div class="article">
  <h1>heading</h1>
  <p>paragraph</p>
  <img src="/images/img-1.jpg" alt="alt for image">
</div>
';

$domDocument = new DOMDocument();
$domDocument->loadHTML($content);
$domElemsToRemove = [];

$domXpath = new DOMXpath($domDocument);
$nodes = $domXpath->query('//div[@class="article"]/img');


$newNode ="<div style='background: transparent url(/images/img-1.jpg) no-repeat; width: inherit; height: inherit; background-position: center center; background-size: cover; width: 566px; height: 576px;'>alt for new image</div>";
$newDom = $domDocument->createDocumentFragment();
$newDom->appendXML($newNode);


foreach ($nodes as $node) {
    $node->parentNode->appendChild($newDom);
    $node->parentNode->removeChild($node);
}

echo $domDocument->saveHTML();
?>

【讨论】:

  • 这个全部替换。假设我在文章中是否有其他元素,如 p、h1 等......不应该被替换。正如我所说的从整个 html 中替换文章类中的 img 标签。
  • 请检查更新的问题,以便您理解。
  • 我明白你的问题,但我现在很忙。稍后将编辑我的答案。
【解决方案4】:

有没有办法用下面的 div 标签替换 img 标签?

是

一)。 DOM(首选方式)

b)。 正则表达式

这两种方法已经在其他答案中实现,使用你喜欢的一种

注意:如果 html 是由 php 动态生成的,我建议您使用 preg_match_all regex here 提取 alt 和 src 属性值,然后从中创建一个字符串,这会给你更多的灵活性,例如:

$str ='<div class="article"><img src="/images/img-1.jpg" alt="alt for image"></div>';

preg_match_all('`src=(?:[\'"])(.*)[\'"].*alt=(?:[\'"])(.*)[\'"].*`U', $str, $matches);

$desiredHTML = <<<HTML
<div class="article">
 <div style="background: transparent url({$matches[1][0]}) no-repeat;
 background-position: center center; background-size: cover; width: 566px; 
 height: 576px;">{$matches[2][0]}</div>
</div>
HTML;

是否可以使用父 div 的宽度和高度?

是的 通过使用以下 js 代码,您可以做到这一点,因为您无法在不渲染的情况下找出 article div 的高度,并且您希望它们以像素为单位,您必须使用 javascript

var cl = document.getElementsByClassName('article');
    for (var i = 0; i <= cl.length; i++)
    {
        var width = cl[i].style.width;
        var height = cl[i].style.height;
        cl[i].firstElementChild.style.width = width;
        cl[i].firstElementChild.style.height = height;
    };

如果可能的话,我想使用 str_replace 函数吗?

NO,使用 str_replace 函数是不可能的。

【讨论】:

    【解决方案5】:
    1. 为此,您需要使用 preg_match 函数
    2. 尝试将高度和宽度设置为“继承”

    对于您的问题,试试这个:

    $string = ' <div class="article">
                    <img src="/images/img-1.jpg" alt="alt for image">
                </div>';
    preg_match('@<div class="article">(.*?)</div>@is', $string, $replace);
    preg_match('/<img src="(.*?)" alt="(.*?)">/', $string, $matches);
    
    $string = str_replace($replace[1], '<div style="background: transparent url('.$matches[1].') no-repeat; background-position: center center; background-size: cover; width: inherit; height: inherit;">'.$matches[2].'</div>', $string);
    

    【讨论】:

    • OP 问题的答案在哪里?
    • 问题是:有没有办法用下面的 div 标签替换 img 标签?
    【解决方案6】:

    要从旧 html 转到新 html,我们需要知道两件事:

    1. src 属性
    2. alt 属性

    一旦我们知道这两个值,我们就可以轻松地创建新的 html 格式。我这样做如下:

    <?php
    $orig_html = <<<HERE
    <div class="article">
      <img src="http://lorempixel.com/400/200" alt="alt for image">
    </div>
    HERE;
    
    echo new_html($orig_html);
    
    /* helper function to get the value of an attribute:
    $attribute: the attribute you want to check (e.g. src)
    $source: The html you want it to parse */
    function get_attribute($attribute, $source) {
        $query  = '/' . $attribute . '="([^"]*)"/i';
        $result = array();
        preg_match($query, $source, $result);
        return $result[1];
    }
    
    /* helper function to return new html from the old html
    $source: the old html */
    function new_html($source) {
        $src = get_attribute('src', $source);
        $alt = get_attribute('alt', $source);
    
        return <<<HERE
     <div class="article">
       <div style="background: transparent url($src) no-repeat;
       background-position: center center; background-size: cover;">$alt</div>
      </div>
    HERE;
    }
    ?>
    

    我们不能用php来读取父类(文章类)的宽高,除非在标记中定义了宽高。从您的示例来看,这些值似乎不在标记中,所以我假设这些尺寸是由 css 提供的?

    相反,您始终可以使用以下 css 设置图像样式: .article &gt; div {width: 100%; height: 100%;}。

    【讨论】:

    • 我想从所有 html 文档中替换。
    • 假设 $article 是完整的 html,然后打印 $article 现在应该替换 img 的版本到 div 和其他相同。
    • @NavinRauniyar 我不关注你的 cmets。 $article 会是一个完整的 html 页面吗?比如like this?
    • 在这种情况下,我建议使用@mlivan 的方法,你最终设法让它工作了吗?
    【解决方案7】:

    你可以试试这样的:

    $content = "this is something with an <img src=\"test.png\"/> in it.";
    $replaceWith = '<div style="background:url($1)"></div>';
    $content = preg_replace('/<img\s+src="([^"]+)"[^>]+>/i', $replaceWith, $content); 
    echo $content;
    

    根据您的标记更改$replaceWith。

    【讨论】:

    • 太棒了。但我说的是只替换 .article div 中的那些图像。有什么建议吗?
    • 如果您尝试更改 .article div 中的 img,那么您应该使用名为 DomDocument 的 PHP 原生库。
    【解决方案8】:

    是的。

    但是 str_replace 不能单独做到这一点。

    $article =<<<'EOT'
      <div class="article">
        <img src="/images/img-1.jpg" alt="alt for image">
      </div>
    EOT;
    
    // img -> div
    $res = str_replace('<img', '<div', $article);
    // src -> style
    $res = preg_replace('/src="([^"]+)"/i', 'style="background: transparent url($1) no-repeat; background-position: center center; background-size: cover; width: 566px; height: 576px;"', $res);
    // alt -> innerHTML
    $res = preg_replace('/ alt="(.*)">/i', '>$1</div>', $res);
    echo $res;
    

    【讨论】:

      【解决方案9】:

      使用preg_replace:

      //your html code in a variable
      $source = '<div class="article">
        <img src="/images/img-1.jpg" alt="alt for image1">
      </div>
      <div class="article">
        <img src="/images/img-5.jpg" alt="alt for image5">
      </div>';
      
      //class
      class PregReplace{
          private static $instance;
          private $source;
          public $css = array('width'=>'600','height'=>'800','background-size'=>'cover','background-position'=>'center center','background'=>'transparent url($1) no-repeat');
          private $replace;
          private $result;
          private $pattern = '/\<div\s?class="article">\n?\r?\n?.*img\s?src="(.*?)"\salt="(.*?)".*\n?\r?\n?\<\/div\>/m';
          public function __construct(){
      
          }
      
          public function loadreplace(){
              $this->replace='<div class="article">
           <div style="background:'.$this->css['background'].'; background-position:'.$this->css['background-position'].'; background-size:'.$this->css['background-size'].'; width:'.$this->css['width'].'px; 
           height: '.$this->css['height'].'px;">$2</div>
          </div>';
          }
      
          public function setcss($array){
              $this->css = $array;
          }
          public function setsource($value){
              $this->source = $value;
              return $this;
          }
          public function setreplace($value){
              $this->replace = $value;
          }
          public function replacing(){
              $this->loadreplace();
              $this->result = preg_replace($this->pattern,$this->replace,$this->source);
              return $this;
          }
          public function result(){
              return $this->result;
          }
      }
      
      //process with preg_replace
      $result = new PregReplace();
      //you can set your css
      $result->css['width'] = '566';
      $result->css['height'] = '576';
      //
      var_dump($result->setsource($source)->replacing()->result());
      

      【讨论】:

      • 这仅在
        匹配时替换,但我只想从
        意思是这个里面可能还有p,h3等其他元素但是只是想替换img...
      【解决方案10】:

      这是我的方法,从 php 调用普通的 Java Script:

      <div class="article">
          <img src="../images/img-1.jpg" alt="alt for image">
      </div>
      
      <?php
      $removeOldContent = '<script>document.getElementsByClassName("article")[0].remove();</script>';
      $newContent = '<div class="article"><div style="background: transparent url(../images/img-1.jpg) no-repeat;
       background-position: center center; background-size: cover; width: 566px;
       height: 576px;">alt for image</div></div>';
      
      $content = $removeOldContent . $newContent;
      
      // this could be you replacing condition
      // false will keep old content
      // true will remove old content and view new content
      if (false)
          echo $content;
      

      【讨论】:

        【解决方案11】:

        您可以将文件读入字符串,根据需要替换,然后写回新文件或覆盖原始文件。无论如何,我可能只是为 div 添加一个类。内联 css 很痛苦。

        【讨论】:

          【解决方案12】:

          这个方法几乎全是preg_replace;它确实有一些不错的补充:

          1. CSS 值 w x h 作为替换的一部分添加。
          2. 所有其他主要值(class、href 和 alt)都被动态替换。

          它基本上使用了两种模式,第一种解析CSS,第二种替换&lt;div&gt;。

          代码:

          <?php
          
          $str = '<div class="article"><img src="/images/image.png" alt="alt for image"></div>';
          $css = '<style> .article { font-size:16px; font-weight:bold; width:566px; height:576px; } </style>
          ';
          
          function replace($str, $css) {
          
              preg_match( '@>\s\.(.+)\s{\s(.*)\s}@', $css, $res);
          
                  $style['class'] = $res[1];
                  $attrs = explode("; ", $res[2]);
          
                  foreach ($attrs as $attr) {
                          if (strlen(trim($attr)) > 0) {
                          $kv = explode(":", trim($attr));
                          $style[trim($kv[0])] = trim($kv[1]);
                      }
                  }
          
          $rep = '<div class="$1">
           <div style="background: transparent url($2) no-repeat; 
           background-position: center center; background-size: cover; width: '.$style['width'].';
           height: '.$style['height'].'">$3</div>
          </div>
          ';
          
              return preg_replace( '@.+class="(.+)"><.*="(.+)"\\salt="(.+)".+@', $rep, $str );
          }
              $str = replace($str, $css);
          ?>
          
          <html>
          <head>
          <?php echo $css; ?>
          </head>
          <body>
          <?php echo $str; ?>
          </body>
          </html>
          

          示例:

          http://ideone.com/TJHR1b

          【讨论】:

            【解决方案13】:

            你可以使用replaceWith method:

            .replaceWith() 方法与大多数 jQuery 方法一样,返回 jQuery 对象,以便其他方法可以链接到它。然而, 必须注意的是,返回的是原始的 jQuery 对象。这 object 指的是已经从 DOM 中移除的元素,而不是 替换它的新元素。

            .replaceWith() 方法删除所有数据和事件处理程序 与被移除的节点相关联。

            $('.article img').replaceWith(function(i, v){
                return $('<div/>', {
                    style: 'background-image: url('+this.src+')',
                    html: '<div style="background: transparent url(/images/img-1.jpg)no-repeat;background-position: center center; background-size: cover; width: 566px; height: 576px;">alt for image</div>'
                })
            })
            

            或

            echo "$('.article img').replaceWith(function(i, v){
                        return $('<div/>', {
                            style: 'background-image: url('+this.src+')',
                            html: '<div style=\"background: transparent url(/images/img-1.jpg)no-repeat;background-position: center center; background-size: cover; width: 566px; height: 576px;\">alt for image</div>'
                        })
                    })";
            

            Here is my jsFiddle.

            【讨论】:

            • 我说的是 php 而不是 jquery。
            • 您可以将此脚本代码转换为php。表示将此脚本代码放入 echo "..." 。
            • 感谢感谢 :)
            • 我编辑的更多解释。你可以检查一下。我希望你能正确地低调。
            • 当你逐字复制某些东西时,即使是文档,你必须链接到文档并引用格式复制的文本,否则它看起来像抄袭。
            【解决方案14】:

            这将完成您正在尝试做的事情。希望这会有所帮助。

            $prev_str = '<div class="article"><img src="pics/flower.jpg" alt="alt for image"></div>';
            preg_match('/'.preg_quote("<div class=\"").'(.*?)'.preg_quote("\"><img").'/is', $prev_str, $class);
            $class_name=$class[1];//article
            preg_match('/'.preg_quote("<img src=\"").'(.*?)'.preg_quote("\" alt=\"").'/is', $prev_str, $image);
            $image_path=$image[1];//pics/flower.jpg
            preg_match('/'.preg_quote("alt=\"").'(.*?)'.preg_quote("\"><").'/is', $prev_str, $alt);
            $alt=$alt[1];//alt for image
            //size that we are going to use in the div as well image div
            $width="200px";
            $height="200px";
            echo '
            <style>
            div.article{
                min-height:'.$height.';
                width:'.$width.';
            }
            </style>';
            /** additional hints in css formatting
            div.article div{
                //display: inline-block;
                //width:inherit;
                //height:inherit;
                //width:100%;
                //height:100%;
            }
            **/
            echo '<div class="'.$class_name.'">';
            echo '<div style="background: transparent url('.$image_path.') no-repeat;
             background-position: center center; background-size: cover;width:'.$height.'; 
             height: '.$width.';">'.$alt.'</div>
            </div>';
            

            【讨论】:

            • 这可能不是最好的答案,但为什么投反对票?如果需要否决,最好评论原因。 :) 酷.. 这个答案已经过测试,它很简单并且可以清楚地完成提问者的需求:)
            猜你喜欢
            • 2018-03-15
            • 2016-03-26
            • 2016-07-04
            • 2017-02-02
            • 2017-10-20
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多