<?php
$html = <<< EOF
<p>Commodity Exchange on 5 April 2016 settled as following graph:</p>
<p><img alt=\"\" src=\"ckeditor/plugins/imageuploader/uploads/986dfdea.png\"
style=\"height:163px; width:650px\" /></p></p>
<p>end of string</p>
EOF;


/*
$doc = new DOMDocument();
$doc->loadHTML($html);
$doc->preserveWhiteSpace = false;
// all links in document

$arr = $doc->getElementsByTagName("div"); // DOMNodeList Object
foreach($arr as $item) { // DOMElement Object
$div = preg_replace('/\s+/im', '', $item->textContent);

//echo $item->textContent."\n";
if(empty($div)){
$link = $doc->createElement('br');
$doc->parentNode->replaceChild($link, $item);
}
}

echo $doc->saveHTML();
*/
$html = tidy_repair_string($html,array(
						   'output-html'   => true,
						   'wrap'           => 80,
						   'show-body-only' => true,
						   'clean' => true,
						   'input-encoding' => 'utf8',
						   'output-encoding' => 'utf8',
										  ));


$dom = new DOMDocument();
$dom->loadHtml($html);



$x = new DOMXpath($dom);
foreach($x->query('//p/img') as $pImg){
	//get image name
	$imgFileName = basename(str_replace('"', "", $pImg->getAttribute("src")));
	$replace = $dom->createTextNode("#$imgFileName");
	$pImg->parentNode->replaceChild($replace, $pImg);
	# loadHTML causes a !DOCTYPE tag to be added, so remove it:
	$dom->removeChild($dom->firstChild);
	# it also wraps the code in <html><body></body></html>, so remove that:
	$dom->replaceChild($dom->firstChild->firstChild, $dom->firstChild);
	echo str_replace(array("<body>", "</body>"), "", $dom->saveHTML());

}
