- mb_convert_encoding: documentation ( source)
- preg_match: documentation ( source)
<?php
$html = <<<EOD
<p>С этой формы приходят заявки <a href="https://site.com/lack_tech.php">https://site.com/lack_tech.php</a></p>
<p>Или что ты имеешь ввиду?</p>
<div class="attachment_files_message">
<p>Прикреплённые файлы:</p>
<a href="http://site.com/public/uploads/kylticket/2670/Screenshot_1.png" target="_blank">Screenshot_1.png</a>
</div>
EOD;
$dom = new DOMDocument();
$dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query('//a[@target="_blank"]') as $OurNode) {
if (preg_match('~\.(?:jpe?g|png)$~i', $OurNode->getAttribute('href'))) {
$fragment = $dom->createDocumentFragment();
$aNode = $dom->createElement('a');
$aNode->setAttribute('data-fancybox', 'gallery'); // + data-fancybox
$aNode->nodeValue = '';
$aNode->setAttribute('href', $OurNode->getAttribute('href'));
$img = $dom->createElement('img');
$img->setAttribute("src", $OurNode->getAttribute('href'));
$img->setAttribute("alt", "");
$img->setAttribute("class", "tmp_class");
$aNode->appendChild($img);
$fragment->appendChild($aNode);
$OurNode->parentNode->replaceChild($fragment, $OurNode);
}
}
echo mb_convert_encoding($dom->saveHTML(), 'UTF-8', 'HTML-ENTITIES');