将超链接和 Class 添加到字符串中的每个图像

Add Hyperlink and Class to every image within a string

我正在使用 Summernote 来 post 博客,但我正在使用代码片段将图像直接上传到服务器而不是在文本本身中,代码如下所示:

<script>$(document).ready(function() {
$("#summernote").summernote({
         callbacks: {
        onImageUpload : function(files, editor, welEditable) {

             for(var i = files.length - 1; i >= 0; i--) {
                     sendFile(files[i], this);
            }
        }
    }
    });
});
function sendFile(file, el) {
var form_data = new FormData();
form_data.append('file', file);
$.ajax({
    data: form_data,
    type: "POST",
    url: 'editor-upload.php',
    cache: false,
    contentType: false,
    processData: false,
    success: function(url) {
        $(el).summernote('editor.insertImage', url);
    }
});
}
</script>

<?php
if(empty($_FILES['file']))
{
    exit();
}
$errorImgFile = "./img/img_upload_error.jpg";
$temp = explode(".", $_FILES["file"]["name"]);
$newfilename = round(microtime(true)) . '.' . end($temp);
$destinationFilePath = './img-uploads/'.$newfilename ;
if(!move_uploaded_file($_FILES['file']['tmp_name'], $destinationFilePath)){
    echo $errorImgFile;
}
else{
    echo $destinationFilePath;
}

?>

我现在正在尝试将 Lightbox 包含到嵌入的图像中,但无法找到一种方法来单独更改 img 标签来执行此操作?举个例子;

$string = '<img src="firstimg.jpg"> a little bit of text <img src="secondimg.jpg">';

我需要将它转换成类似于

的东西
<a class="example-image-link" href="firstimg.jpg" data-lightbox="example-set"><img class="example-image" src="firstimg.jpg"></a> a little bit of text <a class="example-image-link" href="secondimg.jpg" data-lightbox="example-set"><img class="example-image" src="secondimg.jpg"></a>

我四处搜索但没有找到任何帮助?任何帮助,将不胜感激!

let $string = `<img src="firstimg.jpg"> a little bit of text <img src="secondimg.jpg" >`
let parser = new DOMParser()
let _document = parser.parseFromString($string, "text/html")
let ele = _document.getElementsByTagName("IMG")
for(let i = 0; i < ele.length; i++) {
let wrapper = _document.createElement('a'); 
wrapper.classList = ["example-image-link"]
wrapper.href = ele[i].src
wrapper.setAttribute('data-lightbox', 'Hello World!');
let myImg =  ele[i]
wrapper.appendChild(myImg.cloneNode(true)); 
myImg.parentNode.replaceChild(wrapper, myImg);
}

let newStr = `${_document.getElementsByTagName("BODY")[0].innerHTML}`
console.log(newStr)

你可以试试上面的逻辑