Подтвердить что ты не робот

Замените img на background-image div с помощью php

Есть ли способ заменить тег img тегом div, как показано ниже?

Оригинальный 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 i.e. класса статьи в моем примере вместо определения фиксированного width: 566px; height: 576px;?

Если возможно, я хочу использовать функцию str_replace.

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

Edit:

В статье класса может быть несколько элементов, и в классе класса div могут быть другие элементы, из которых мне нужно изменить img на div.

Edit2:

Я имел в виду, что у меня может быть любой контент внутри статьи div и просто хочу заменить img на div.

У меня может быть:

<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 как

From:

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

To:

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

Ответ 1

Вы можете использовать собственную библиотеку DOM для PHP, чтобы найти и заменить 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

Ответ 2

используйте simplehtmldom php-класса (http://simplehtmldom.sourceforge.net/) вы можете найти и изменить HTML-Dom с помощью селекторов типа CSS.

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

Ответ 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();
?>

Ответ 4

  • Для этого вам необходимо работать с функцией preg_match
  • Попробуйте установить высоту и ширину как "наследовать"

Для вашей проблемы попробуйте следующее:

$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);

Ответ 5

Чтобы перейти от старого html к новому html, нам нужно знать две вещи:

  • атрибут src
  • атрибут 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 > div {width: 100%; height: 100%;}.

Ответ 6

Вы можете попробовать что-то вроде этого:

$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 в соответствии с вашей разметкой.

Ответ 7

Есть ли способ заменить тег img тегом div, как показано ниже?

Да

а). DOM (предпочтительный способ)

б). REGEX

оба метода уже реализованы в других ответах, используйте тот, который вам нравится

Примечание:, если html генерируется динамически php, я бы посоветовал извлечь атрибуты alt и src с помощью preg_match_all regex здесь, а затем создайте строку из этого, что даст вам больше гибкости, например:

$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.

Ответ 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());

Ответ 10

Вот мой подход, вызовите нормальную Java Script из php:

<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. Inline css - это боль.

Ответ 12

Вы можете использовать replaceWith method:

Метод .replaceWith(), как и большинство методов jQuery, возвращает jQuery, чтобы на него могли быть наложены другие методы. Однако, следует отметить, что возвращается исходный объект jQuery. Эта объект ссылается на элемент, который был удален из 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>'
            })
        })";

Вот мой jsFiddle.

Ответ 13

Это выполнит то, что вы пытаетесь сделать. Надеюсь, это поможет.

$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>';

Ответ 14

Этот метод почти полностью preg_replace; у него есть несколько приятных дополнений:

  • Значения CSS w x h добавляются как часть замены.
  • Все остальные основные значения (class, href и alt) динамически заменяются.

В основном он использует два шаблона, первый раз анализирует CSS, а второй заменяет <div>.

Код

<?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="(.+)"[email protected]', $rep, $str );
}
    $str = replace($str, $css);
?>

<html>
<head>
<?php echo $css; ?>
</head>
<body>
<?php echo $str; ?>
</body>
</html>

Пример:

http://ideone.com/TJHR1b