【问题标题】:Replace image path to base64 string with several containing string用几个包含字符串替换base64字符串的图像路径
【发布时间】:2019-10-08 01:50:29
【问题描述】:

我有一个包含“https://tryout.pendukasi.id/upload/”的字符串,我想将每个包含“https://tryout.pendukasi.id/upload/”的字符串替换为“data:image/jpeg; base64”。

代码:

foreach (StorageFile file in files)
{
    string soalP = file.Path;
    if (question.Pertanyaan.ToString().Contains("https://tryout.pendidikan.id/upload/"))
    {
        byte[] imageArray = System.IO.File.ReadAllBytes(soalP);
            string base64ImageRepresentation = Convert.ToBase64String(imageArray);
            soal = Regex.Replace(question.Pertanyaan.ToString(), "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
    }
}

我有一个问题,如果字符串包含一个“https://tryout.pendukasi.id/upload/”,那么字符串被替换成功,但是如果它包含多个“https://tryout.pendukasi.id/upload/”,例如:"<p>Perhatikan ayat-ayat Surat al-Falaq berikut ini!<br /><img src=\"https://tryout.pendidikan.id/upload/3-1.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-2.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-3.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-4.JPG\" /><br /><img src=\"https://tryout.pendidikan.id/upload/3-5.JPG\" /><br />Urutan ayat dalam Surat al-Falaq yang benar adalah ….</p>",那么字符串就没有成功改变。如何解决这个问题?

【问题讨论】:

    标签: c# string uwp tobase64string


    【解决方案1】:

    发生这种情况是因为您正在逐个文件替换,并且之前的更改一直被以下更改:

    soal = Regex.Replace(question.Pertanyaan.ToString(), "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
    

    一种方法是将您的正则表达式替换字符串保存到一个变量中。 通过这样做,您的替换不会被覆盖:

    string soal = question.Pertanyaan.ToString();
    
    foreach (StorageFile file in files)
    {
        string soalP = file.Path;
        if (soal.Contains("https://tryout.pendidikan.id/upload/"))
        {
            byte[] imageArray = System.IO.File.ReadAllBytes(soalP);
                string base64ImageRepresentation = Convert.ToBase64String(imageArray);
                soal = Regex.Replace(soal, "\"https://tryout.pendidikan.id/upload/" + file.Name + "\"", "data:image/jpeg;base64," + base64ImageRepresentation);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 2019-09-10
      • 1970-01-01
      相关资源
      最近更新 更多