过滤img src以删除目录中的文件,如何剪切php中的数组删除文件


filter img src to remove file in directory, How to cut the array remove file in php

我有一个如下的html结构,它是随机的div标记和img标记,这些也存储在数据库中
现在我必须过滤下面字符串中的img src,以删除不在此结构中但存储在目录中的文件,
在前端使用jquery或服务器端使用php获得这种结构中的src的最佳方法是什么
有什么建议吗?非常感谢!!

在前端

<div class="h1">content<div>
<div class="h1" style="">content</div>
<div class="h1" style="">...</div>
<div class="h2">...</div>
<div class="h1" style="">content</div>
<img src="u_img/5/1.png" style="" class="">
<div class="link" style="">link: http://...</div>
<img src="u_img/5/14.jpeg" style="" class="">
<div class="h1" style=""..</div>
<img src="u_img/5/3.png" style="" class="">

在数据库中

<div class="h1">content<div><div class="h1" style="">content</div><div class="h1" style="">...</div><div class="h2">...</div><div class="h1" style="">content</div><img src="u_img/5/1.png" style="" class=""><div class="link" style="">link: http://...</div><img src="u_img/5/14.jpeg" style="" class=""><div class="h1" style=""..</div><img src="u_img/5/3.png" style="" class="">

更新
如果我通过下面的jquery到php文件在数组post的前端存储中获得这些img src,那么如何删除那些不在这个数组中的文件

var srcArray=$('img').map(function(){
    return $(this).attr('src');
});
var fd = new FormData(uf[0]);
fd.append('srcArray',srcArray);
$.ajax({
    type: "POST", url: "img_clean.php",
    data: fd,
    processData: false, contentType: false,
})

php

$srcArray = $_POST['srcArray']; 
//How to delete file not in the array?
foreach($srcArray as $row){
    $dir = "u_img_p/".$id;  
        //unlink($dir.'/'.$row);
    } 
}

使用attr()获取src

 $('img').each(function(){
    var $src=$(this).attr('src'); //prop() for latest versio of jquery.
    //do you stuff ..$src is the source 
 });

或者可以使用map()将所有源存储在阵列中

var srcArray=$('img').map(function(){
    return $(this).attr('src'); //prop() for latest versio of jquery.
 });

CCD_ 2将具有所有的图像源。

注:$('img')选择文档中存在的所有图像标记。。小心

编辑后更新

$.ajax({
 type: "POST", 
 url: "img_clean.php",
 data: {'postedValue':srcArray},
 processData: false, contentType: false,
})

PHP

$srcArray = $_POST['postedValue']; 
foreach($srcArray as $row){
  $dir = "u_img_p/".$id;  
   unlink($dir.'/'.$row); //delete it
  } 
}

使用正则表达式应该可以帮助

preg_replace("/<img[^>]+'>/i", "empty", $mydatabasecontent)
var sources = [];
$("img").each(function(){
   sources.push($(this).prop("src")); // for older jQuery versions use attr("src");
});

这将把所有的图像源广告到一个阵列。