用 php 将 img 替换为 background-image div

     2023-02-24     215

关键词:

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

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

原始html:

<div class="article">
  <img src="/images/img-1.jpg" >
</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" >
</div>

或者我可能有:

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

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

发件人:

<img src="/images/img-1.jpg"  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 会更好。 【参考方案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" >
  <br>
  <h3>
  <p>paragraph</p>
    <img src="images/image2.png" >
  </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" >
</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" >
</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 提取 altsrc 属性值,然后从中创建一个字符串,这会给你更多的灵活性,例如:

$str ='<div class="article"><img src="/images/img-1.jpg" ></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】:
    为此,您需要使用 preg_match 函数 尝试将高度和宽度设置为“继承”

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

$string = ' <div class="article">
                <img src="/images/img-1.jpg" >
            </div>';
preg_match('@<div class="article">(.*?)</div>@is', $string, $replace);
preg_match('/<img src="(.*?)" >/', $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,我们需要知道两件事:

    src 属性 alt 属性

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

<?php
$orig_html = <<<HERE
<div class="article">
  <img src="http://lorempixel.com/400/200" >
</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" >
  </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('/ >/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" >
</div>
<div class="article">
  <img src="/images/img-5.jpg" >
</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="(.*?)"\s.*\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" >
</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;它确实有一些不错的补充:

    CSS 值 w x h 作为替换的一部分添加。 所有其他主要值(classhrefalt)都被动态替换。

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

代码

<?php

$str = '<div class="article"><img src="/images/image.png" ></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="(.+)"><.*="(.+)"\\s.+@', $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" ></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
$;
$;
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>';

【讨论】:

这可能不是最好的答案,但为什么投反对票?如果需要否决,最好评论原因。 :) 酷.. 这个答案已经过测试,它很简单并且可以清楚地完成提问者的需求:)

使用 PHP 将特定的 RGB 颜色替换为另一个图像

】使用PHP将特定的RGB颜色替换为另一个图像【英文标题】:ReplacethespecificRGBcolorwithanotherimageusingPHP【发布时间】:2016-04-2821:13:17【问题描述】:我从https://***.com/a/32710756/1620626导出了一个完美的颜色替换脚本。我想用图像背景替换... 查看详情

用 php 将每个 font size="" 替换为 font-size: ;如何? [关闭]

】用php将每个fontsize=""替换为font-size:;如何?[关闭]【英文标题】:Replacewithphpeachfontsize=""tofont-size:;howto?[closed]【发布时间】:2014-11-1819:23:07【问题描述】:我想用font-size="somenumber"替换每次出现的fontsize="... 查看详情

PHP用空白替换动态字符串

】PHP用空白替换动态字符串【英文标题】:PHPreplaceadynamicstringwithblank【发布时间】:2016-06-0115:06:10【问题描述】:我有这个img标签<imgsrc="../img/tmp/pack_mini_5753_.jpg?time=1464793546"class="imgmimg-thumbnail">我想删除字符串?time=1464793546。... 查看详情

使用 PHP 将 URLS 中的空格替换为 %20

】使用PHP将URLS中的空格替换为%20【英文标题】:UsingPHPReplaceSPACESinURLSwith%20【发布时间】:2012-03-0316:14:03【问题描述】:我希望用%20替换url中的所有空格实例。我将如何使用正则表达式来做到这一点?谢谢!【问题讨论】:是否... 查看详情

批处理将文本中的变量名替换为变量值并删除定义赋值语句

...等号的赋值语句。3.D:\aa目录下有多个txt文件,要全部替换。批处理可放在相同文件夹下。4.高手请进,谢绝“用查找-替换”之类的小儿科。50分回报。REM====::以REM开头的,整行删除,属代码注释。DIMobjApp::以DIM开头的整行删... 查看详情

利用正则表达式替换img标签的问题

...src="images/emoji/blush.png">123321,需要用正则表达式替换为:blush:123321如何用JS来编写?textarea中可能有多个img标签,都需要替换参考技术Acontent=content.replace(/<img([^>]+)blush\:([^>]+)>(\d+)/ig,"<img$1blush:$3$2>"... 查看详情

如何使用 php 将 .docx、xslx、img、txt 等任何文件转换为 PDF 预览?

】如何使用php将.docx、xslx、img、txt等任何文件转换为PDF预览?【英文标题】:Howcaniconvertanyfilelike.docx,xslx,img,txttoPDFpreviewusingphp?【发布时间】:2020-02-0709:53:30【问题描述】:如果我单击表格中的文档链接,我需要将任何文件转换... 查看详情

PHP - 替换 <img> 标签并返回 src

】PHP-替换<img>标签并返回src【英文标题】:PHP-replace<img>tagsandreturnsrc【发布时间】:2012-11-2620:26:24【问题描述】:任务是用&lt;div&gt;标签和src属性替换给定字符串中的所有&lt;img&gt;标签作为内部文本。在寻找... 查看详情

为啥 PHP 将 $_COOKIE 中的加号替换为空格?

】为啥PHP将$_COOKIE中的加号替换为空格?【英文标题】:WhydoesPHPreplacepluseswithspacesin$_COOKIE?为什么PHP将$_COOKIE中的加号替换为空格?【发布时间】:2013-01-0106:22:34【问题描述】:所以根据我对PHP和cookie的理解,如果我使用setcookie()... 查看详情

php怎么给文本图片地址加img标签

比如$a33的变量里面包含一个网址jpg的文本,如何把它替换成加过IMG标签的呢,感谢因为你这个问题没有描述清楚,看了下你和楼上的回答,有了一个初步的了解,实际上,你是在那个把一段字符串中的“图片url”替换为“<imgs... 查看详情

react.js 替换 img src onerror

】react.js替换imgsrconerror【英文标题】:react.jsReplaceimgsrconerror【发布时间】:2016-03-0922:19:24【问题描述】:我有一个反应组件,它是列表中的详细视图。如果图像不存在并且出现404错误,我正在尝试将图像替换为默认图像。我通... 查看详情

将问号 (?) 替换为 (\\?)

】将问号(?)替换为(\\\\\\\\?)【英文标题】:Replaceaquestionmark(?)with(\\\\?)将问号(?)替换为(\\\\?)【发布时间】:2011-06-0102:00:28【问题描述】:我正在尝试定义一个模式来匹配其中带有问号(?)的文本。在正则表达式中,问号被认为是“... 查看详情

一些用过的我常忘记的小知识(web前端)

背景图片固定:background-attachment:fixed将图片的尺寸从中心点开始改变:backgroun-position:center background-size:**旋转:div1.style.transform="rotate(180deg)"窗口滚动条大概是17px将鼠标的样式改变为指定图片:cursor:url("/img/cursor.png"),defaul 查看详情

如何使用php用“and”替换字符串中的最后一个逗号?

】如何使用php用“and”替换字符串中的最后一个逗号?【英文标题】:Howtoreplacelastcommainstringwith"and"usingphp?【发布时间】:2017-06-0509:35:25【问题描述】:我正在尝试使用strrchr()和str_replace()将文本中最后出现的逗号替换为... 查看详情

将多行合并为一列,同时用原始表中的“名称”字段替换键

】将多行合并为一列,同时用原始表中的“名称”字段替换键【英文标题】:Mergemultiplerowsintoacolumnwhilereplacingthekeyswitha\'name\'fieldfromtheoriginaltable【发布时间】:2022-01-2206:53:42【问题描述】:我有一个连接表,其中包含“account_id... 查看详情

java利用freemarker导出world

...ml的格式      3、编辑xml文件内容,将‘用户名‘替换成->${username}、‘简介‘替换成->${resume}、将图片内容用变量->${img}替换。        --》  4、修改xml文件后缀名,将xml修改为ftl格式。      5、... 查看详情

sed ack 搜索/用字符串替换换行符

】sedack搜索/用字符串替换换行符【英文标题】:sedacksearch/replacelinebreakwithstring【发布时间】:2021-06-2116:08:19【问题描述】:我查看了一些SO线程,但没有一个对我的具体情况有所帮助。我正在尝试将我从php5.6接管到php8.0的PHP应用... 查看详情

sql怎么用replace将'(单引号)替换为\'

UPDATE [表名]SET [列名] = replace([列名], '''', '\\''')WHER 条件注:第二个参数为四个单引号,第三个参数反斜杠后面位三个单引号参考技术AUPDATE[表名]SET[列名]=replace([列名],''',... 查看详情