[CLOSED] how to replace img src with Regex

  1. #1

    [CLOSED] how to replace img src with Regex

    i want to replace img tag's src ,because the src is out of server, so i want to download the pic and save to server,

    <ext:FieldContainer runat="server" LabelWidth="65" Margin="4" FieldLabel="图片下载">
                                <Items>
                                    <ext:Button runat="server" Icon="DiskDownload" ID="btn_picdownload">
                                        <DirectEvents>
                                            <Click OnEvent="SavePics">
                                                <EventMask ShowMask="True"></EventMask>
                                            </Click>
                                        </DirectEvents>
                                    </ext:Button>
                                </Items>
                            </ext:FieldContainer>
    
                            <ext:HtmlEditor runat="server" ID="he_cont" AnchorHorizontal="100%" AnchorVertical="-78">
                            </ext:HtmlEditor>
     protected void SavePics(object sender, DirectEventArgs e)
            {
                var editorContent = he_cont.Text;
                 
                Regex reg = new Regex(@"(?is)<img[^>]*?src=(['""\s]?)((?:(?!topics)[^'""\s])*)\1[^>]*?>");  //here is regex, could you please check it again? is it right?
                foreach (Match m in reg.Matches(editorContent))
                { 
                    var url = m.Groups[2].Value; // here is the img's src value
                    var uploadedFile = new UploadedFile(url, "yyyy-MM-dd-HH-mm-ss");
                    var mywebclient = new WebClient(); 
                    try
                    {
                        mywebclient.DownloadFile(url, uploadedFile.PhysicalFilePath); //download the remote pic to my server.
                    }
                    catch (Exception ex)
                    {
                        X.Msg.Alert("消息", "下载失败");
                    }
                    var wp = uploadedFile.WebPath;  //here is web path, i want to replace the url(the img's src value) with wp, 
                    // then set the new editorContent  to htmleditor's text
                }
                
            }
        public class UploadedFile
        {
            public string WebPath;
            public string PhysicalFilePath;
            private readonly string _fileFormat;
            private readonly string _fileName;
            private string _newFileName;
            private readonly string _y =  System.DateTime.Now.Year.ToString(CultureInfo.InvariantCulture);
            private readonly string _m = System.DateTime.Now.Month.ToString(CultureInfo.InvariantCulture);
            public UploadedFile(string filename, string fileFormat)
            {
                this._fileName = filename;
                this._fileFormat = fileFormat; 
                CreateNewFileName();
                CreatePhysicalUploadedPath();
                CreatePhysicalFilePath();
                CreateWebPath();
            }
             
            private void CreateNewFileName()
            {
                var ran = new Random();
                this._newFileName = DateTime.Now.ToString(@"yyyy-MM-dd-HH-mm-ss") + "-" + ran.Next(100, 999)
                                  + Path.GetExtension(this._fileName);
            }
            private void CreatePhysicalFilePath()
            {
                var ran = new Random();
                string sNewName = DateTime.Now.ToString(this._fileFormat) + "-" + ran.Next(100, 999)
                                  + Path.GetExtension(this._fileName);
                this.PhysicalFilePath = HttpContext.Current.Server.MapPath("/Uploads/" + _y + "/" + _m + "/" + sNewName);
            }
            private void CreateWebPath()
            {
                this.WebPath = "/Uploads/" + _y + "/" + _m + "/" + this._newFileName;
            }
            private void CreatePhysicalUploadedPath()
            {
                string pathMoth = HttpContext.Current.Server.MapPath("/Uploads/" + _y + "/" + _m);
                if (!Directory.Exists(pathMoth))
                {
                    Directory.CreateDirectory(pathMoth);
                }
            }
        }
    could you please help me?
    Last edited by Daniil; Oct 15, 2013 at 6:44 AM. Reason: [CLOSED]
  2. #2
    Hi @hdsoso,

    Maybe, you could use a String's Replace method.

    Example
    <%@ Page Language="C#" %>
    
    <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
    
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            string img = "<img src=\"some src\"></img>",
                   someTextWithImg = string.Format("some surrounding text| {0} |some surrounding text", img),
                   newSrc = "resources/images/test.png";
    
            Regex regex = new Regex("<img.+?src=[\"'](.+?)[\"'].+?>");
    
            string src = regex.Match(someTextWithImg).Groups[1].Value;
    
            X.Msg.Alert("Result", someTextWithImg.Replace(src, newSrc)).Show();
        }
    </script>
    
    <!DOCTYPE html>
    <html>
    <head runat="server">
        <title>Ext.NET v2 Example</title>
    </head>
    <body>
        <form runat="server">
            <ext:ResourceManager runat="server" />
        </form>
    </body>
    </html>
  3. #3
    Quote Originally Posted by Daniil View Post
    Hi @hdsoso,

    Maybe, you could use a String's Replace method.

    Example
    <%@ Page Language="C#" %>
    
    <%@ Register Assembly="Ext.Net" Namespace="Ext.Net" TagPrefix="ext" %>
    
    <script runat="server">
        protected void Page_Load(object sender, EventArgs e)
        {
            string img = "<img src=\"some src\"></img>",
                   someTextWithImg = string.Format("some surrounding text| {0} |some surrounding text", img),
                   newSrc = "resources/images/test.png";
    
            Regex regex = new Regex("<img.+?src=[\"'](.+?)[\"'].+?>");
    
            string src = regex.Match(someTextWithImg).Groups[1].Value;
    
            X.Msg.Alert("Result", someTextWithImg.Replace(src, newSrc)).Show();
        }
    </script>
    
    <!DOCTYPE html>
    <html>
    <head runat="server">
        <title>Ext.NET v2 Example</title>
    </head>
    <body>
        <form runat="server">
            <ext:ResourceManager runat="server" />
        </form>
    </body>
    </html>
    thanks, but you replace only one img's src and replace with same text, my original text have multiple img tags , and each img's src will be replace with different text.
  4. #4
    Hello!

    The logic should be the same but you should apply it to the whole text and using for loop all found items.

    What exactly doesn't work?
  5. #5
    Quote Originally Posted by Baidaly View Post
    Hello!

    The logic should be the same but you should apply it to the whole text and using for loop all found items.

    What exactly doesn't work?
    protected void SavePics(object sender, DirectEventArgs e)
            {
                var editorContent = he_cont.Text;
                 
               // Regex reg = new Regex(@"(?is)<img[^>]*?src=(['""\s]?)((?:(?!topics)[^'""\s])*)\1[^>]*?>");
                Regex reg = new Regex("<img.+?src=[\"'](.+?)[\"'].+?>");
                foreach (Match m in reg.Matches(editorContent))
                { 
                    var url = m.Groups[1].Value; 
                    var uploadedFile = new UploadedFile(url, "yyyy-MM-dd-HH-mm-ss");
                    var mywebclient = new WebClient(); 
                    try
                    {
                        mywebclient.DownloadFile(url, uploadedFile.PhysicalFilePath); 
                    }
                    catch (Exception ex)
                    {
                        X.Msg.Alert("消息", "下载失败");
                    }
                    var wp = uploadedFile.WebPath;
                    editorContent.Replace(url, wp);// here replace the original src with new one? 
                }
                he_cont.Text = editorContent;
            }
    sorry,is it ok?
  6. #6
    Quote Originally Posted by hdsoso View Post
    sorry,is it ok?
    Does it work?
    Geoffrey McGill
    Founder

Similar Threads

  1. [CLOSED] replace the communication failure message
    By JCarlosF in forum 2.x Legacy Premium Help
    Replies: 1
    Last Post: May 14, 2013, 1:45 AM
  2. ComboBoxBase.Select() replace old value
    By teamsar in forum 2.x Help
    Replies: 0
    Last Post: Feb 05, 2013, 9:50 AM
  3. interface of Window when replace v1.3 -> v1.6
    By Kai_it in forum 1.x Help
    Replies: 1
    Last Post: Jan 24, 2013, 4:23 AM
  4. [CLOSED] PartialView to replace the contents of a div.
    By mattwoberts in forum 1.x Legacy Premium Help
    Replies: 3
    Last Post: Feb 22, 2011, 3:33 PM
  5. [CLOSED] Add or replace item in Store
    By macap in forum 1.x Legacy Premium Help
    Replies: 1
    Last Post: Apr 22, 2010, 3:17 PM

Posting Permissions