利用正则表达式搜索富文本框中的图片链接
项目中有一需求,删除一条资讯[新闻],要求删除资讯相关的标题图片和资讯内容中插入的图片。资讯内容采用富文本框实现。
界面如下:
代码如下:
/// <summary>
/// 删除资讯
/// </summary>
/// <param name="id"></param>
public void RemoveInfo(Int32 id)
{
DataTable dt = SQLHelper.ExecuteTable(CommandType.Text,"SELECT PICURL,CONTENT FROM [INFO] WHERE ID="+id);
if (dt == null || dt.Rows.Count == 0)
throw new Exception("没有该条新闻可以删除");
//获得资讯标题图片
string picUrl = Convert.ToString(dt.Rows[0]["PICURL"]);
//获得资讯内容[内容中可能包含插入的图片连接]
string content = Convert.ToString(dt.Rows[0]["CONTENT"]);
List<string> contentImgs = new List<string>();
//利用正则表达式寻找待删除的资讯内容中插入的图片
Regex regImg = new Regex("<img.*?src=\"([^\"]+)\".*?/>");
//利用正则表达式寻找src属性的文件名
Regex regJpg = new Regex("[\\w]{14}_[\\d]{4}.jpg");
//找出所有匹配项
MatchCollection ms = regImg.Matches(content);
foreach (Match m in ms)
{
//m.Value;//m.Value是每个匹配项的字串,如下格式:
//<img src="/kindeditor/attached/image/20120526/20120526184503_0781.jpg" alt="" />
//regJpg.Match(m.Value).Value;//从上面匹配字串中再次匹配出xxx.jpg文件名,如下格式:
//20120526184503_0781.jpg
contentImgs.Add(regJpg.Match(m.Value).Value);
}
//从数据库删除资讯条目
if (SQLHelper.ExecuteNonQuery(CommandType.Text, SQL_DELETE, new SqlParameter("@ID", id)) == 1)
{
string appPath = ServerInfo.GetRootPath();//获得Web项目运行时物理路径
File.Delete(appPath +"\\images\\infopic\\"+picUrl);
foreach (string item in contentImgs)
{
File.Delete(appPath +"\\kindeditor\\attached\\image\\"+item.Substring(0,8)+"\\"+item);
}
}
}