php - How to add quotes to the src attribute of the img tag -


i have correct several posts on database these:

<a href="somelink.html"><img src=someimage.jpg border=1 alt="some text"></a> 

so need to:

  • remove border=1 attribute (str_replace job)
  • add quotes @ begin , end of src attribute: src="someimage.jpg"
  • close img tag adding /> @ end of tag

one thing tried parse dom , src source:

$doc = new domdocument();     $body = $this->removeunnecessarytags($body);     $doc->loadhtml($this->removeunnecessarytags($body));     $imagetags = $doc->getelementsbytagname('img');      foreach($imagetags $tag) {         $result[] = [ 'src' => $tag->getattribute('src'), 'alt' => $tag->getattribute('alt') ];     } 

i know can done regex regex knowledge not good. ideas?

thanks

all need use domdocument features , libxml options:

$html = '<a href="somelink.html"><img src=someimage.jpg border=1 alt="some text"></a>';  libxml_use_internal_errors(true); $dom = new domdocument; $dom->loadhtml($html, libxml_html_nodefdtd | libxml_html_noimplied);  $result = $dom->savexml($dom->documentelement);  echo $result; 

libxml_html_nodefdtd prevents add automatically dtd when dtd missing. libxml_html_noimplied prevents add html , body tags when missing.

the savexml method save document xml compliant syntax, solves self-closing tags problem. $dom->documentelement used parameter avoid xml declaration automatically added.(*)

whatever method use (savexml or savehtml) double quotes used enclose attributes automatically.

(*) remove eventual dtd too, if want preserve it, can use workaround remove xml declaration:

$result = $dom->savexml(); $result = substr($result, strpos($result, "\n") + 1); 

Comments

Popular posts from this blog

javascript - AngularJS custom datepicker directive -

javascript - jQuery date picker - Disable dates after the selection from the first date picker -