html - Replace img to background-image div with php -


is there way replace img tag div tag below?

original html:

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

replaced 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 image</div> </div> 

(optional) possible use width , height parent div i.e. article class in example instead of defining fixed width: 566px; height: 576px;?

if it's possible, want use str_replace function.

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

edit:

there may multiple elements class article , there may other elements inside article class div , need change img div.

edit2:

i meaning if may have content inside article div , want replace img div.

i may have:

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

or may have:

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

so, may have inside .article div , wanted replace img div like

from:

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

to:

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

you can use php’s native dom library found , replace html. wrote example, adapt case. hope help.

updated code:

$html_str = '<div class="article newclass" id="some_id">   <h1>heading</h1>   <p>paragraph</p>   <img src="images/image.png" alt="alt image">   <br>   <h3>   <p>paragraph</p>     <img src="images/image2.png" alt="alt image3">   </h3>   </div>';  $dom = new domdocument(); $dom->loadhtml($html_str); $xpath = new domxpath($dom);  foreach ($xpath->query('//div[contains(@class, "article")]//img') $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; } 

replace function stay same change part manage dom


Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -