You can use XPath to only target the img nodes you want:
$dom = new DOMDocument;
libxml_use_internal_errors(true);
$dom->loadHTMLFile($filePath, LIBXML_HTML_NODEFDTD);
// or $dom->loadHTML($htmlString, LIBXML_HTML_NODEFDTD);
$xp = new DOMXPath($dom);
$nodeList = $xp->query('//img[starts-with(@src, "media/lib/pics/")]');
$newPath = 'my/new/path/';
foreach ($nodeList as $node) {
$imgFileName = basename($node->getAttribute('src'));
$imgNode = $dom->createElement('img'); // create a new img element to replace the old img node
$imgNode->setAttribute('src', $newPath . $imgFileName);
$node->parentNode->replaceChild($imgNode, $node);
}
$result = $dom->saveHTML();
XPath query details:
// # everywhere in the DOM tree
img # an img element
[ # open a predicate
starts-with(@src, "media/lib/pics/") # with a src attribute that starts with "media/lib/pics/"
] # close the predicate