title: Parsing HTML and replacing strings
body: <p>I have a large quantity of partial HTML stored in a CMS database.</p>
  
  <p>I'm looking for a way to go through the HTML and find any <code>&lt;a&gt;&lt;/a&gt;</code> tags that don't have a title and add a title to them based on the contents of the tags.</p>
  
  <p>So if I had <code>&lt;a href="somepage"&gt;some text&lt;/a&gt;</code> I'd like to modify the tag to look like:</p>
  
  <p><code>&lt;a title="some text" href="somepage"&gt;&lt;/a&gt;</code></p>
  
  <p>Some tags already have a title and some anchor tags have nothing between them.</p>
  
  <p>So far I've managed to make some progress with php and regex.</p>
  
  <p>But I can't seem to be able to get the contents of the anchors, it just displays either a 1 or a 0.</p>
  
  <pre><code>&lt;?php
  $file = "test.txt";
  $handle = fopen("$file", "r");
  $theData = fread($handle, filesize($file));
  $line = explode("\r\n", $theData);
  
  $regex = '/^.*&lt;a ((?!title).)*$/'; //finds all lines that don't contain an anchor with a title
  $regex2 = '/&lt;a .*&gt;&lt;\/a&gt;/'; //finds all lines that have nothing between the anchors
  $regex3 = '/&lt;a.*?&gt;(.+?)&lt;\/a&gt;/'; //finds the contents of the anchors
  
  foreach ($line as $lines)
  {
    if (!preg_match($regex2, $lines) &amp;&amp; preg_match($regex, $lines)){
      $tags = $lines;
      $contents = preg_match($regex3, $tags);
      $replaced = str_replace("&lt;a ", "&lt;a title=\"$contents\" ", $lines);
      echo $replaced ."\r\n";
    }
    else {
    echo $lines. "\r\n";
    }
  }
  ?&gt;
  </code></pre>
  
  <p>I understand regex is probably not the best way to parse HTML so any help or alternate suggestions would be greatly appreciated.</p>