How to parse out links and img src references from body copy? I need to modify links and img references in the body of nodes and comments. MPD already gave me good advice regarding using a script.

Is there an easy way in Drupal or PHP to parse out all the links in the body copy?
It's never easy to do something like this because parsing HTML is a bit hit-and-miss, depending on how well formatted the input is.

I've always found the best way to do it is to load the HTML into a DOMDocument object, loop through and change whatever element attributes/values I need to, then use the DOMDocument to give me the new output.

This is a very rough example but hopefully it'll give you the idea:

$html = '
  &lt;p&gt;Blah blah blah&lt;/p&gt;
  &lt;p&gt;&lt;a href="/some-path" title="A Title"&gt;Link Text&lt;/a&gt;
  &lt;/p&gt;&lt;p&gt;&lt;img src="/some-path.jpg" alt="Some alt" /&gt;&lt;/p&gt;';

$doc = new DOMDocument;

// This is a reasonable use of the @ operator as malformed HTML will produce
// a lot of warnings. Please don't shoot me ;)
@$doc-&gt;loadHTML($html); 

// Get the links.
$links = $doc-&gt;getElementsByTagName('a');
foreach ($links as $link) {
  // Change the value of an attribute based on the current value.
  if ($link-&gt;getAttribute('href') == '/some-path') {
    $link-&gt;setAttribute('href', '/some-other-path');
  }
}

// Get the images.
$images = $doc-&gt;getElementsByTagName('img');
foreach ($images as $image) {
  // Change the value of an attribute based on the current value.
  if ($image-&gt;getAttribute('src') == '/some-path.jpg') {
    $image-&gt;setAttribute('src', '/some-other-path.jpg');
  }
}

// Get the new HTML
$new_html = $doc-&gt;saveHTML();

// Strip out the tags that loadHTML() introduces to get the clean HTML.
$patterns = array("/^\&lt;\!DOCTYPE.*?&lt;html&gt;&lt;body&gt;/si", "!&lt;/body&gt;&lt;/html&gt;$!si");
$body_text = preg_replace($patterns, '', $new_html);

// Update the node body.
$node-&gt;body[$node-&gt;language][0]['value'] = $body_text;


EDIT

I knew I'd seen a good question about this on SO; have a look at How to parse and process HTML with PHP? for a good discussion on the subject in general.