title: How to use php dom document to remove and replace tags
body: <p>I have image tag <code>&lt;img src="path_to_file.png"&gt;</code> but I want that the image tag be converted to link in mobile site.
  So I want img to be converted to an href:</p>
  
  <pre><code>&lt;a href="path_to_file.png" target="_blank"&gt;Click here to open in new tab&lt;/a&gt;
  </code></pre>
  
  <p>I am getting started with php dom.
  I could get all the attribute listed.</p>
  
  <pre><code>$newdocument = new DOMDocument();
  $newdocument-&gt;loadHTML();
  $getimagetag = $doc-&gt;getElementsByTagName('img');
  foreach($getimagetag as $tag) {
      echo $src=$tag-&gt;getAttribute('src');
  }
  </code></pre>
  
  <p>But how do we get the src attribute , then remove the img tag completely because it contains other parameter like height and length and then create new tag of link?</p>
  
  <p>Hi guys I could get it done from php dom using following code</p>
  
  <pre><code>$input="&lt;img src='path_to_file.png' height='50'&gt;";
      $doc = new DOMDocument();
      $doc-&gt;loadHTML($input);
      $imageTags = $doc-&gt;getElementsByTagName('img');
      foreach($imageTags as $tag) {
          $src=$tag-&gt;getAttribute('src'); 
          $a=$doc-&gt;createElement('a','click here to open in new tab');
          $a-&gt;setAttribute('href',$src);
          $a-&gt;setAttribute('style','color:red;');
          $tag-&gt;parentNode-&gt;replaceChild($a,$tag);
          } 
          $input=$doc-&gt;saveHTML();
  echo $input; 
  </code></pre>
  
  <p>The create element can also be used to put text between <code>&lt;a&gt;&lt;/a&gt;</code> ie Click...new tab.</p>
  
  <p>replacechild is used to remove $tag i.e. <code>img</code> and replace it with <code>a</code> tag.
  By setting attribute, we can add other parameters like style,target etc.</p>
  
  <p>I used php dom in the end because I only wanted the data that I get from mysql to be converted and not the other elements like logo of website. Ofcourse it can be possible using javascript too.</p>
  
  <p>Thanks</p>
  
  <p>@dave chen for  javascript way and pointing to detecting mobile link.</p>
  
  <p>@nate for pointing me to a answer.</p>